{"repo_name": "adk-java", "file_name": "/adk-java/core/src/main/java/com/google/adk/tools/retrieval/BaseRetrievalTool.java", "inference_info": {"prefix_code": "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools.retrieval;\n\nimport com.google.adk.tools.BaseTool;\nimport com.google.genai.types.FunctionDeclaration;\nimport com.google.genai.types.Schema;\nimport java.util.Collections;\nimport java.util.Optional;\n\n/** Base class for retrieval tools. */\npublic abstract class BaseRetrievalTool extends BaseTool {\n public BaseRetrievalTool(String name, String description) {\n super(name, description);\n }\n\n public BaseRetrievalTool(String name, String description, boolean isLongRunning) {\n super(name, description, isLongRunning);\n }\n\n ", "suffix_code": "\n}\n", "middle_code": "@Override\n public Optional declaration() {\n Schema querySchema =\n Schema.builder().type(\"STRING\").description(\"The query to retrieve.\").build();\n Schema parametersSchema =\n Schema.builder()\n .type(\"OBJECT\")\n .properties(Collections.singletonMap(\"query\", querySchema))\n .build();\n return Optional.of(\n FunctionDeclaration.builder()\n .name(this.name())\n .description(this.description())\n .parameters(parametersSchema)\n .build());\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "java", "sub_task_type": null}, "context_code": [["/adk-java/core/src/main/java/com/google/adk/tools/retrieval/VertexAiRagRetrieval.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools.retrieval;\n\nimport static com.google.common.collect.ImmutableList.toImmutableList;\n\nimport com.google.adk.models.LlmRequest;\nimport com.google.adk.tools.ToolContext;\nimport com.google.cloud.aiplatform.v1.RagContexts;\nimport com.google.cloud.aiplatform.v1.RagQuery;\nimport com.google.cloud.aiplatform.v1.RetrieveContextsRequest;\nimport com.google.cloud.aiplatform.v1.RetrieveContextsRequest.VertexRagStore.RagResource;\nimport com.google.cloud.aiplatform.v1.RetrieveContextsResponse;\nimport com.google.cloud.aiplatform.v1.VertexRagServiceClient;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport com.google.genai.types.GenerateContentConfig;\nimport com.google.genai.types.Retrieval;\nimport com.google.genai.types.Tool;\nimport com.google.genai.types.VertexRagStore;\nimport com.google.genai.types.VertexRagStoreRagResource;\nimport io.reactivex.rxjava3.core.Completable;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.List;\nimport java.util.Map;\nimport javax.annotation.Nonnull;\nimport javax.annotation.Nullable;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * A retrieval tool that fetches context from Vertex AI RAG.\n *\n *

This tool allows to retrieve relevant information based on a query using Vertex AI RAG\n * service. It supports configuration of rag resources and a vector distance threshold.\n */\npublic class VertexAiRagRetrieval extends BaseRetrievalTool {\n private static final Logger logger = LoggerFactory.getLogger(VertexAiRagRetrieval.class);\n private final VertexRagServiceClient vertexRagServiceClient;\n private final String parent;\n private final List ragResources;\n private final Double vectorDistanceThreshold;\n private final VertexRagStore vertexRagStore;\n private final RetrieveContextsRequest.VertexRagStore apiVertexRagStore;\n\n public VertexAiRagRetrieval(\n @Nonnull String name,\n @Nonnull String description,\n @Nonnull VertexRagServiceClient vertexRagServiceClient,\n @Nonnull String parent,\n @Nullable List ragResources,\n @Nullable Double vectorDistanceThreshold) {\n super(name, description);\n this.vertexRagServiceClient = vertexRagServiceClient;\n this.parent = parent;\n this.ragResources = ragResources;\n this.vectorDistanceThreshold = vectorDistanceThreshold;\n\n // For Gemini 2\n VertexRagStore.Builder vertexRagStoreBuilder = VertexRagStore.builder();\n if (this.ragResources != null) {\n vertexRagStoreBuilder.ragResources(\n this.ragResources.stream()\n .map(\n ragResource ->\n VertexRagStoreRagResource.builder()\n .ragCorpus(ragResource.getRagCorpus())\n .build())\n .collect(toImmutableList()));\n }\n if (this.vectorDistanceThreshold != null) {\n vertexRagStoreBuilder.vectorDistanceThreshold(this.vectorDistanceThreshold);\n }\n this.vertexRagStore = vertexRagStoreBuilder.build();\n\n // For runAsync\n RetrieveContextsRequest.VertexRagStore.Builder apiVertexRagStoreBuilder =\n RetrieveContextsRequest.VertexRagStore.newBuilder();\n if (this.ragResources != null) {\n apiVertexRagStoreBuilder.addAllRagResources(this.ragResources);\n }\n if (this.vectorDistanceThreshold != null) {\n apiVertexRagStoreBuilder.setVectorDistanceThreshold(this.vectorDistanceThreshold);\n }\n this.apiVertexRagStore = apiVertexRagStoreBuilder.build();\n }\n\n @Override\n @CanIgnoreReturnValue\n public Completable processLlmRequest(\n LlmRequest.Builder llmRequestBuilder, ToolContext toolContext) {\n LlmRequest llmRequest = llmRequestBuilder.build();\n // Use Gemini built-in Vertex AI RAG tool for Gemini 2 models or when using Vertex AI API Model\n boolean useVertexAi = Boolean.parseBoolean(System.getenv(\"GOOGLE_GENAI_USE_VERTEXAI\"));\n if (useVertexAi\n && (llmRequest.model().isPresent() && llmRequest.model().get().startsWith(\"gemini-2\"))) {\n GenerateContentConfig config =\n llmRequest.config().orElse(GenerateContentConfig.builder().build());\n ImmutableList.Builder toolsBuilder = ImmutableList.builder();\n if (config.tools().isPresent()) {\n toolsBuilder.addAll(config.tools().get());\n }\n toolsBuilder.add(\n Tool.builder()\n .retrieval(Retrieval.builder().vertexRagStore(this.vertexRagStore).build())\n .build());\n logger.info(\n \"Using Gemini built-in Vertex AI RAG tool for model: {}\", llmRequest.model().get());\n llmRequestBuilder.config(config.toBuilder().tools(toolsBuilder.build()).build());\n return Completable.complete();\n } else {\n // Add the function declaration to the tools\n return super.processLlmRequest(llmRequestBuilder, toolContext);\n }\n }\n\n @Override\n public Single> runAsync(Map args, ToolContext toolContext) {\n String query = (String) args.get(\"query\");\n logger.info(\"VertexAiRagRetrieval.runAsync called with query: {}\", query);\n return Single.fromCallable(\n () -> {\n logger.info(\"Retrieving context for query: {}\", query);\n RetrieveContextsRequest retrieveContextsRequest =\n RetrieveContextsRequest.newBuilder()\n .setParent(this.parent)\n .setQuery(RagQuery.newBuilder().setText(query))\n .setVertexRagStore(this.apiVertexRagStore)\n .build();\n logger.info(\"Request to VertexRagService: {}\", retrieveContextsRequest);\n RetrieveContextsResponse response =\n this.vertexRagServiceClient.retrieveContexts(retrieveContextsRequest);\n logger.info(\"Response from VertexRagService: {}\", response);\n if (response.getContexts().getContextsList().isEmpty()) {\n logger.warn(\"No matching result found for query: {}\", query);\n return ImmutableMap.of(\n \"response\",\n String.format(\n \"No matching result found with the config: resources: %s\", this.ragResources));\n } else {\n logger.info(\n \"Found {} matching results for query: {}\",\n response.getContexts().getContextsCount(),\n query);\n ImmutableList contexts =\n response.getContexts().getContextsList().stream()\n .map(RagContexts.Context::getText)\n .collect(toImmutableList());\n logger.info(\"Returning contexts: {}\", contexts);\n return ImmutableMap.of(\"response\", contexts);\n }\n });\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/AgentTool.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools;\n\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.google.adk.JsonBaseModel;\nimport com.google.adk.SchemaUtils;\nimport com.google.adk.agents.BaseAgent;\nimport com.google.adk.agents.LlmAgent;\nimport com.google.adk.events.Event;\nimport com.google.adk.runner.InMemoryRunner;\nimport com.google.adk.runner.Runner;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.FunctionDeclaration;\nimport com.google.genai.types.Part;\nimport com.google.genai.types.Schema;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.Map;\nimport java.util.Optional;\n\n/** AgentTool implements a tool that allows an agent to call another agent. */\npublic class AgentTool extends BaseTool {\n\n private final BaseAgent agent;\n private final boolean skipSummarization;\n\n public static AgentTool create(BaseAgent agent, boolean skipSummarization) {\n return new AgentTool(agent, skipSummarization);\n }\n\n public static AgentTool create(BaseAgent agent) {\n return new AgentTool(agent, false);\n }\n\n protected AgentTool(BaseAgent agent, boolean skipSummarization) {\n super(agent.name(), agent.description());\n this.agent = agent;\n this.skipSummarization = skipSummarization;\n }\n\n @Override\n public Optional declaration() {\n FunctionDeclaration.Builder builder =\n FunctionDeclaration.builder().description(this.description()).name(this.name());\n\n Optional agentInputSchema = Optional.empty();\n if (agent instanceof LlmAgent llmAgent) {\n agentInputSchema = llmAgent.inputSchema();\n }\n\n if (agentInputSchema.isPresent()) {\n builder.parameters(agentInputSchema.get());\n } else {\n builder.parameters(\n Schema.builder()\n .type(\"OBJECT\")\n .properties(ImmutableMap.of(\"request\", Schema.builder().type(\"STRING\").build()))\n .required(ImmutableList.of(\"request\"))\n .build());\n }\n return Optional.of(builder.build());\n }\n\n @Override\n public Single> runAsync(Map args, ToolContext toolContext) {\n\n if (this.skipSummarization) {\n toolContext.actions().setSkipSummarization(true);\n }\n\n Optional agentInputSchema = Optional.empty();\n if (agent instanceof LlmAgent llmAgent) {\n agentInputSchema = llmAgent.inputSchema();\n }\n\n final Content content;\n if (agentInputSchema.isPresent()) {\n SchemaUtils.validateMapOnSchema(args, agentInputSchema.get(), true);\n try {\n content =\n Content.fromParts(Part.fromText(JsonBaseModel.getMapper().writeValueAsString(args)));\n } catch (JsonProcessingException e) {\n return Single.error(\n new RuntimeException(\"Error serializing tool arguments to JSON: \" + args, e));\n }\n } else {\n Object input = args.get(\"request\");\n content = Content.fromParts(Part.fromText(input.toString()));\n }\n\n Runner runner = new InMemoryRunner(this.agent, toolContext.agentName());\n // Session state is final, can't update to toolContext state\n // session.toBuilder().setState(toolContext.getState());\n return runner\n .sessionService()\n .createSession(toolContext.agentName(), \"tmp-user\", toolContext.state(), null)\n .flatMapPublisher(session -> runner.runAsync(session.userId(), session.id(), content))\n .lastElement()\n .map(Optional::of)\n .defaultIfEmpty(Optional.empty())\n .map(\n optionalLastEvent -> {\n if (optionalLastEvent.isEmpty()) {\n return ImmutableMap.of();\n }\n Event lastEvent = optionalLastEvent.get();\n Optional outputText =\n lastEvent\n .content()\n .flatMap(Content::parts)\n .filter(parts -> !parts.isEmpty())\n .flatMap(parts -> parts.get(0).text());\n\n if (outputText.isEmpty()) {\n return ImmutableMap.of();\n }\n String output = outputText.get();\n\n Optional agentOutputSchema = Optional.empty();\n if (agent instanceof LlmAgent llmAgent) {\n agentOutputSchema = llmAgent.outputSchema();\n }\n\n if (agentOutputSchema.isPresent()) {\n return SchemaUtils.validateOutputSchema(output, agentOutputSchema.get());\n } else {\n return ImmutableMap.of(\"result\", output);\n }\n });\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/FunctionCallingUtils.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools;\n\nimport static com.google.common.base.Preconditions.checkArgument;\n\nimport com.fasterxml.jackson.databind.BeanDescription;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition;\nimport com.google.adk.JsonBaseModel;\nimport com.google.common.base.Strings;\nimport com.google.genai.types.FunctionDeclaration;\nimport com.google.genai.types.Schema;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Parameter;\nimport java.lang.reflect.ParameterizedType;\nimport java.lang.reflect.Type;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\n\n/** Utility class for function calling. */\npublic final class FunctionCallingUtils {\n\n private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();\n\n public static FunctionDeclaration buildFunctionDeclaration(\n Method func, List ignoreParams) {\n String name =\n func.isAnnotationPresent(Annotations.Schema.class)\n && !func.getAnnotation(Annotations.Schema.class).name().isEmpty()\n ? func.getAnnotation(Annotations.Schema.class).name()\n : func.getName();\n FunctionDeclaration.Builder builder = FunctionDeclaration.builder().name(name);\n if (func.isAnnotationPresent(Annotations.Schema.class)\n && !func.getAnnotation(Annotations.Schema.class).description().isEmpty()) {\n builder.description(func.getAnnotation(Annotations.Schema.class).description());\n }\n List required = new ArrayList<>();\n Map properties = new LinkedHashMap<>();\n for (Parameter param : func.getParameters()) {\n String paramName =\n param.isAnnotationPresent(Annotations.Schema.class)\n && !param.getAnnotation(Annotations.Schema.class).name().isEmpty()\n ? param.getAnnotation(Annotations.Schema.class).name()\n : param.getName();\n if (ignoreParams.contains(paramName)) {\n continue;\n }\n required.add(paramName);\n properties.put(paramName, buildSchemaFromParameter(param));\n }\n builder.parameters(\n Schema.builder().required(required).properties(properties).type(\"OBJECT\").build());\n\n Type returnType = func.getGenericReturnType();\n if (returnType != Void.TYPE) {\n Type realReturnType = returnType;\n if (returnType instanceof ParameterizedType) {\n ParameterizedType parameterizedReturnType = (ParameterizedType) returnType;\n String returnTypeName = ((Class) parameterizedReturnType.getRawType()).getName();\n if (returnTypeName.equals(\"io.reactivex.rxjava3.core.Maybe\")\n || returnTypeName.equals(\"io.reactivex.rxjava3.core.Single\")) {\n returnType = parameterizedReturnType.getActualTypeArguments()[0];\n if (returnType instanceof ParameterizedType) {\n ParameterizedType maybeParameterizedType = (ParameterizedType) returnType;\n returnTypeName = ((Class) maybeParameterizedType.getRawType()).getName();\n }\n }\n if (returnTypeName.equals(\"java.util.Map\")\n || returnTypeName.equals(\"com.google.common.collect.ImmutableMap\")) {\n return builder.response(buildSchemaFromType(returnType)).build();\n }\n }\n throw new IllegalArgumentException(\n \"Return type should be Map or Maybe or Single, but it was \"\n + realReturnType.getTypeName());\n }\n return builder.build();\n }\n\n static FunctionDeclaration buildFunctionDeclaration(JsonBaseModel func, String description) {\n // Create function declaration through json string.\n String jsonString = func.toJson();\n checkArgument(!Strings.isNullOrEmpty(jsonString), \"Input String can't be null or empty.\");\n FunctionDeclaration declaration = FunctionDeclaration.fromJson(jsonString);\n declaration = declaration.toBuilder().description(description).build();\n if (declaration.name().isEmpty() || declaration.name().get().isEmpty()) {\n throw new IllegalArgumentException(\"name field must be present.\");\n }\n return declaration;\n }\n\n private static Schema buildSchemaFromParameter(Parameter param) {\n Schema.Builder builder = Schema.builder();\n if (param.isAnnotationPresent(Annotations.Schema.class)\n && !param.getAnnotation(Annotations.Schema.class).description().isEmpty()) {\n builder.description(param.getAnnotation(Annotations.Schema.class).description());\n }\n switch (param.getType().getName()) {\n case \"java.lang.String\" -> builder.type(\"STRING\");\n case \"boolean\", \"java.lang.Boolean\" -> builder.type(\"BOOLEAN\");\n case \"int\", \"java.lang.Integer\" -> builder.type(\"INTEGER\");\n case \"double\", \"java.lang.Double\", \"float\", \"java.lang.Float\", \"long\", \"java.lang.Long\" ->\n builder.type(\"NUMBER\");\n case \"java.util.List\" ->\n builder\n .type(\"ARRAY\")\n .items(\n buildSchemaFromType(\n ((ParameterizedType) param.getParameterizedType())\n .getActualTypeArguments()[0]));\n case \"java.util.Map\" -> builder.type(\"OBJECT\");\n default -> {\n BeanDescription beanDescription =\n OBJECT_MAPPER\n .getSerializationConfig()\n .introspect(OBJECT_MAPPER.constructType(param.getType()));\n Map properties = new LinkedHashMap<>();\n for (BeanPropertyDefinition property : beanDescription.findProperties()) {\n properties.put(property.getName(), buildSchemaFromType(property.getRawPrimaryType()));\n }\n builder.type(\"OBJECT\").properties(properties);\n }\n }\n return builder.build();\n }\n\n public static Schema buildSchemaFromType(Type type) {\n Schema.Builder builder = Schema.builder();\n if (type instanceof ParameterizedType parameterizedType) {\n switch (((Class) parameterizedType.getRawType()).getName()) {\n case \"java.util.List\" ->\n builder\n .type(\"ARRAY\")\n .items(buildSchemaFromType(parameterizedType.getActualTypeArguments()[0]));\n case \"java.util.Map\", \"com.google.common.collect.ImmutableMap\" -> builder.type(\"OBJECT\");\n default -> throw new IllegalArgumentException(\"Unsupported generic type: \" + type);\n }\n } else if (type instanceof Class clazz) {\n switch (clazz.getName()) {\n case \"java.lang.String\" -> builder.type(\"STRING\");\n case \"boolean\", \"java.lang.Boolean\" -> builder.type(\"BOOLEAN\");\n case \"int\", \"java.lang.Integer\" -> builder.type(\"INTEGER\");\n case \"double\", \"java.lang.Double\", \"float\", \"java.lang.Float\", \"long\", \"java.lang.Long\" ->\n builder.type(\"NUMBER\");\n case \"java.util.Map\", \"com.google.common.collect.ImmutableMap\" -> builder.type(\"OBJECT\");\n default -> {\n BeanDescription beanDescription =\n OBJECT_MAPPER.getSerializationConfig().introspect(OBJECT_MAPPER.constructType(type));\n Map properties = new LinkedHashMap<>();\n for (BeanPropertyDefinition property : beanDescription.findProperties()) {\n properties.put(property.getName(), buildSchemaFromType(property.getRawPrimaryType()));\n }\n builder.type(\"OBJECT\").properties(properties);\n }\n }\n }\n return builder.build();\n }\n\n private FunctionCallingUtils() {}\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/BaseTool.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools;\n\nimport static com.google.common.collect.ImmutableList.toImmutableList;\n\nimport com.google.adk.models.LlmRequest;\nimport com.google.common.collect.ImmutableList;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport com.google.genai.types.FunctionDeclaration;\nimport com.google.genai.types.GenerateContentConfig;\nimport com.google.genai.types.Tool;\nimport io.reactivex.rxjava3.core.Completable;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.Map;\nimport java.util.Optional;\nimport javax.annotation.Nonnull;\nimport org.jspecify.annotations.Nullable;\n\n/** The base class for all ADK tools. */\npublic abstract class BaseTool {\n private final String name;\n private final String description;\n private final boolean isLongRunning;\n\n protected BaseTool(@Nonnull String name, @Nonnull String description) {\n this(name, description, /* isLongRunning= */ false);\n }\n\n protected BaseTool(@Nonnull String name, @Nonnull String description, boolean isLongRunning) {\n this.name = name;\n this.description = description;\n this.isLongRunning = isLongRunning;\n }\n\n public String name() {\n return name;\n }\n\n public String description() {\n return description;\n }\n\n public boolean longRunning() {\n return isLongRunning;\n }\n\n /** Gets the {@link FunctionDeclaration} representation of this tool. */\n public Optional declaration() {\n return Optional.empty();\n }\n\n /** Calls a tool. */\n public Single> runAsync(Map args, ToolContext toolContext) {\n throw new UnsupportedOperationException(\"This method is not implemented.\");\n }\n\n /**\n * Processes the outgoing {@link LlmRequest.Builder}.\n *\n *

This implementation adds the current tool's {@link #declaration()} to the {@link\n * GenerateContentConfig} within the builder. If a tool with function declarations already exists,\n * the current tool's declaration is merged into it. Otherwise, a new tool definition with the\n * current tool's declaration is created. The current tool itself is also added to the builder's\n * internal list of tools. Override this method for processing the outgoing request.\n */\n @CanIgnoreReturnValue\n public Completable processLlmRequest(\n LlmRequest.Builder llmRequestBuilder, ToolContext toolContext) {\n if (declaration().isEmpty()) {\n return Completable.complete();\n }\n\n llmRequestBuilder.appendTools(ImmutableList.of(this));\n\n LlmRequest llmRequest = llmRequestBuilder.build();\n ImmutableList toolsWithoutFunctionDeclarations =\n findToolsWithoutFunctionDeclarations(llmRequest);\n Tool toolWithFunctionDeclarations = findToolWithFunctionDeclarations(llmRequest);\n // If LlmRequest GenerateContentConfig already has a function calling tool,\n // merge the function declarations.\n // Otherwise, add a new tool definition with function calling declaration..\n if (toolWithFunctionDeclarations == null) {\n toolWithFunctionDeclarations =\n Tool.builder().functionDeclarations(ImmutableList.of(declaration().get())).build();\n } else {\n toolWithFunctionDeclarations =\n toolWithFunctionDeclarations.toBuilder()\n .functionDeclarations(\n ImmutableList.builder()\n .addAll(\n toolWithFunctionDeclarations\n .functionDeclarations()\n .orElse(ImmutableList.of()))\n .add(declaration().get())\n .build())\n .build();\n }\n // Patch the GenerateContentConfig with the new tool definition.\n GenerateContentConfig generateContentConfig =\n llmRequest\n .config()\n .map(GenerateContentConfig::toBuilder)\n .orElse(GenerateContentConfig.builder())\n .tools(\n new ImmutableList.Builder()\n .addAll(toolsWithoutFunctionDeclarations)\n .add(toolWithFunctionDeclarations)\n .build())\n .build();\n llmRequestBuilder.config(generateContentConfig);\n return Completable.complete();\n }\n\n /**\n * Finds a tool in GenerateContentConfig that has function calling declarations, or returns null\n * otherwise.\n */\n private static @Nullable Tool findToolWithFunctionDeclarations(LlmRequest llmRequest) {\n return llmRequest\n .config()\n .flatMap(config -> config.tools())\n .flatMap(\n tools -> tools.stream().filter(t -> t.functionDeclarations().isPresent()).findFirst())\n .orElse(null);\n }\n\n /** Finds all tools in GenerateContentConfig that do not have function calling declarations. */\n private static ImmutableList findToolsWithoutFunctionDeclarations(LlmRequest llmRequest) {\n return llmRequest\n .config()\n .flatMap(config -> config.tools())\n .map(\n tools ->\n tools.stream()\n .filter(t -> t.functionDeclarations().isEmpty())\n .collect(toImmutableList()))\n .orElse(ImmutableList.of());\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/LoadArtifactsTool.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// LoadArtifactsTool.java\npackage com.google.adk.tools;\n\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.google.adk.JsonBaseModel;\nimport com.google.adk.models.LlmRequest;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.FunctionDeclaration;\nimport com.google.genai.types.FunctionResponse;\nimport com.google.genai.types.Part;\nimport com.google.genai.types.Schema;\nimport io.reactivex.rxjava3.core.Completable;\nimport io.reactivex.rxjava3.core.Observable;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.Optional;\n\n/**\n * A tool that loads artifacts and adds them to the session.\n *\n *

This tool informs the model about available artifacts and provides their content when\n * requested by the model through a function call.\n */\npublic final class LoadArtifactsTool extends BaseTool {\n public LoadArtifactsTool() {\n super(\"load_artifacts\", \"Loads the artifacts and adds them to the session.\");\n }\n\n @Override\n public Optional declaration() {\n return Optional.of(\n FunctionDeclaration.builder()\n .name(this.name())\n .description(this.description())\n .parameters(\n Schema.builder()\n .type(\"OBJECT\")\n .properties(\n ImmutableMap.of(\n \"artifact_names\",\n Schema.builder()\n .type(\"ARRAY\")\n .items(Schema.builder().type(\"STRING\").build())\n .build()))\n .build())\n .build());\n }\n\n @Override\n public Single> runAsync(Map args, ToolContext toolContext) {\n @SuppressWarnings(\"unchecked\")\n List artifactNames =\n (List) args.getOrDefault(\"artifact_names\", ImmutableList.of());\n return Single.just(ImmutableMap.of(\"artifact_names\", artifactNames));\n }\n\n @Override\n public Completable processLlmRequest(\n LlmRequest.Builder llmRequestBuilder, ToolContext toolContext) {\n return super.processLlmRequest(llmRequestBuilder, toolContext)\n .andThen(appendArtifactsToLlmRequest(llmRequestBuilder, toolContext));\n }\n\n public Completable appendArtifactsToLlmRequest(\n LlmRequest.Builder llmRequestBuilder, ToolContext toolContext) {\n\n return toolContext\n .listArtifacts()\n .flatMapCompletable(\n artifactNamesList -> {\n if (artifactNamesList.isEmpty()) {\n return Completable.complete();\n }\n\n appendInitialInstructions(llmRequestBuilder, artifactNamesList);\n\n return processLoadArtifactsFunctionCall(llmRequestBuilder, toolContext);\n });\n }\n\n private void appendInitialInstructions(\n LlmRequest.Builder llmRequestBuilder, List artifactNamesList) {\n try {\n String instructions =\n String.format(\n \"You have a list of artifacts:\\n %s\\n\\nWhen the user asks questions about\"\n + \" any of the artifacts, you should call the `load_artifacts` function\"\n + \" to load the artifact. Do not generate any text other than the\"\n + \" function call.\",\n JsonBaseModel.getMapper().writeValueAsString(artifactNamesList));\n llmRequestBuilder.appendInstructions(ImmutableList.of(instructions));\n } catch (JsonProcessingException e) {\n throw new IllegalStateException(\"Failed to serialize artifact names to JSON\", e);\n }\n }\n\n private Completable processLoadArtifactsFunctionCall(\n LlmRequest.Builder llmRequestBuilder, ToolContext toolContext) {\n\n LlmRequest currentRequestState = llmRequestBuilder.build();\n List currentContents = currentRequestState.contents();\n\n if (currentContents.isEmpty()) {\n return Completable.complete();\n }\n\n return Iterables.getLast(currentContents)\n .parts()\n .filter(partsList -> !partsList.isEmpty())\n .flatMap(partsList -> partsList.get(0).functionResponse())\n .filter(fr -> Objects.equals(fr.name().orElse(null), \"load_artifacts\"))\n .flatMap(FunctionResponse::response)\n .flatMap(responseMap -> Optional.ofNullable(responseMap.get(\"artifact_names\")))\n .filter(obj -> obj instanceof List)\n .map(obj -> (List) obj)\n .filter(list -> !list.isEmpty())\n .map(\n artifactNamesRaw -> {\n @SuppressWarnings(\"unchecked\")\n List artifactNamesToLoad = (List) artifactNamesRaw;\n\n return Observable.fromIterable(artifactNamesToLoad)\n .flatMapCompletable(\n artifactName ->\n loadAndAppendIndividualArtifact(\n llmRequestBuilder, toolContext, artifactName));\n })\n .orElse(Completable.complete());\n }\n\n private Completable loadAndAppendIndividualArtifact(\n LlmRequest.Builder llmRequestBuilder, ToolContext toolContext, String artifactName) {\n\n return toolContext\n .loadArtifact(artifactName, Optional.empty())\n .flatMapCompletable(\n actualArtifact ->\n Completable.fromAction(\n () ->\n appendArtifactToLlmRequest(\n llmRequestBuilder,\n \"Artifact \" + artifactName + \" is:\",\n actualArtifact)));\n }\n\n private void appendArtifactToLlmRequest(\n LlmRequest.Builder llmRequestBuilder, String prefix, Part artifact) {\n llmRequestBuilder.contents(\n ImmutableList.builder()\n .addAll(llmRequestBuilder.build().contents())\n .add(Content.fromParts(Part.fromText(prefix), artifact))\n .build());\n }\n}\n"], ["/adk-java/contrib/langchain4j/src/main/java/com/google/adk/models/langchain4j/LangChain4j.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.google.adk.models.langchain4j;\n\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.google.adk.models.BaseLlm;\nimport com.google.adk.models.BaseLlmConnection;\nimport com.google.adk.models.LlmRequest;\nimport com.google.adk.models.LlmResponse;\nimport com.google.genai.types.Blob;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.FunctionCall;\nimport com.google.genai.types.FunctionCallingConfigMode;\nimport com.google.genai.types.FunctionDeclaration;\nimport com.google.genai.types.FunctionResponse;\nimport com.google.genai.types.GenerateContentConfig;\nimport com.google.genai.types.Part;\nimport com.google.genai.types.Schema;\nimport com.google.genai.types.ToolConfig;\nimport com.google.genai.types.Type;\nimport dev.langchain4j.Experimental;\nimport dev.langchain4j.agent.tool.ToolExecutionRequest;\nimport dev.langchain4j.agent.tool.ToolSpecification;\nimport dev.langchain4j.data.audio.Audio;\nimport dev.langchain4j.data.image.Image;\nimport dev.langchain4j.data.message.AiMessage;\nimport dev.langchain4j.data.message.AudioContent;\nimport dev.langchain4j.data.message.ChatMessage;\nimport dev.langchain4j.data.message.ImageContent;\nimport dev.langchain4j.data.message.PdfFileContent;\nimport dev.langchain4j.data.message.SystemMessage;\nimport dev.langchain4j.data.message.TextContent;\nimport dev.langchain4j.data.message.ToolExecutionResultMessage;\nimport dev.langchain4j.data.message.UserMessage;\nimport dev.langchain4j.data.message.VideoContent;\nimport dev.langchain4j.data.pdf.PdfFile;\nimport dev.langchain4j.data.video.Video;\nimport dev.langchain4j.exception.UnsupportedFeatureException;\nimport dev.langchain4j.model.chat.ChatModel;\nimport dev.langchain4j.model.chat.StreamingChatModel;\nimport dev.langchain4j.model.chat.request.ChatRequest;\nimport dev.langchain4j.model.chat.request.ToolChoice;\nimport dev.langchain4j.model.chat.request.json.JsonArraySchema;\nimport dev.langchain4j.model.chat.request.json.JsonBooleanSchema;\nimport dev.langchain4j.model.chat.request.json.JsonIntegerSchema;\nimport dev.langchain4j.model.chat.request.json.JsonNumberSchema;\nimport dev.langchain4j.model.chat.request.json.JsonObjectSchema;\nimport dev.langchain4j.model.chat.request.json.JsonSchemaElement;\nimport dev.langchain4j.model.chat.request.json.JsonStringSchema;\nimport dev.langchain4j.model.chat.response.ChatResponse;\nimport dev.langchain4j.model.chat.response.StreamingChatResponseHandler;\nimport io.reactivex.rxjava3.core.BackpressureStrategy;\nimport io.reactivex.rxjava3.core.Flowable;\nimport java.util.ArrayList;\nimport java.util.Base64;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.UUID;\n\n@Experimental\npublic class LangChain4j extends BaseLlm {\n\n private static final TypeReference> MAP_TYPE_REFERENCE =\n new TypeReference<>() {};\n\n private final ChatModel chatModel;\n private final StreamingChatModel streamingChatModel;\n private final ObjectMapper objectMapper;\n\n public LangChain4j(ChatModel chatModel) {\n super(\n Objects.requireNonNull(\n chatModel.defaultRequestParameters().modelName(), \"chat model name cannot be null\"));\n this.chatModel = Objects.requireNonNull(chatModel, \"chatModel cannot be null\");\n this.streamingChatModel = null;\n this.objectMapper = new ObjectMapper();\n }\n\n public LangChain4j(ChatModel chatModel, String modelName) {\n super(Objects.requireNonNull(modelName, \"chat model name cannot be null\"));\n this.chatModel = Objects.requireNonNull(chatModel, \"chatModel cannot be null\");\n this.streamingChatModel = null;\n this.objectMapper = new ObjectMapper();\n }\n\n public LangChain4j(StreamingChatModel streamingChatModel) {\n super(\n Objects.requireNonNull(\n streamingChatModel.defaultRequestParameters().modelName(),\n \"streaming chat model name cannot be null\"));\n this.chatModel = null;\n this.streamingChatModel =\n Objects.requireNonNull(streamingChatModel, \"streamingChatModel cannot be null\");\n this.objectMapper = new ObjectMapper();\n }\n\n public LangChain4j(StreamingChatModel streamingChatModel, String modelName) {\n super(Objects.requireNonNull(modelName, \"streaming chat model name cannot be null\"));\n this.chatModel = null;\n this.streamingChatModel =\n Objects.requireNonNull(streamingChatModel, \"streamingChatModel cannot be null\");\n this.objectMapper = new ObjectMapper();\n }\n\n public LangChain4j(ChatModel chatModel, StreamingChatModel streamingChatModel, String modelName) {\n super(Objects.requireNonNull(modelName, \"model name cannot be null\"));\n this.chatModel = Objects.requireNonNull(chatModel, \"chatModel cannot be null\");\n this.streamingChatModel =\n Objects.requireNonNull(streamingChatModel, \"streamingChatModel cannot be null\");\n this.objectMapper = new ObjectMapper();\n }\n\n @Override\n public Flowable generateContent(LlmRequest llmRequest, boolean stream) {\n if (stream) {\n if (this.streamingChatModel == null) {\n return Flowable.error(new IllegalStateException(\"StreamingChatModel is not configured\"));\n }\n\n ChatRequest chatRequest = toChatRequest(llmRequest);\n\n return Flowable.create(\n emitter -> {\n streamingChatModel.chat(\n chatRequest,\n new StreamingChatResponseHandler() {\n @Override\n public void onPartialResponse(String s) {\n emitter.onNext(\n LlmResponse.builder().content(Content.fromParts(Part.fromText(s))).build());\n }\n\n @Override\n public void onCompleteResponse(ChatResponse chatResponse) {\n if (chatResponse.aiMessage().hasToolExecutionRequests()) {\n AiMessage aiMessage = chatResponse.aiMessage();\n toParts(aiMessage).stream()\n .map(Part::functionCall)\n .forEach(\n functionCall -> {\n functionCall.ifPresent(\n function -> {\n emitter.onNext(\n LlmResponse.builder()\n .content(\n Content.fromParts(\n Part.fromFunctionCall(\n function.name().orElse(\"\"),\n function.args().orElse(Map.of()))))\n .build());\n });\n });\n }\n emitter.onComplete();\n }\n\n @Override\n public void onError(Throwable throwable) {\n emitter.onError(throwable);\n }\n });\n },\n BackpressureStrategy.BUFFER);\n } else {\n if (this.chatModel == null) {\n return Flowable.error(new IllegalStateException(\"ChatModel is not configured\"));\n }\n\n ChatRequest chatRequest = toChatRequest(llmRequest);\n ChatResponse chatResponse = chatModel.chat(chatRequest);\n LlmResponse llmResponse = toLlmResponse(chatResponse);\n\n return Flowable.just(llmResponse);\n }\n }\n\n private ChatRequest toChatRequest(LlmRequest llmRequest) {\n ChatRequest.Builder requestBuilder = ChatRequest.builder();\n\n List toolSpecifications = toToolSpecifications(llmRequest);\n requestBuilder.toolSpecifications(toolSpecifications);\n\n if (llmRequest.config().isPresent()) {\n GenerateContentConfig generateContentConfig = llmRequest.config().get();\n\n generateContentConfig\n .temperature()\n .ifPresent(temp -> requestBuilder.temperature(temp.doubleValue()));\n generateContentConfig.topP().ifPresent(topP -> requestBuilder.topP(topP.doubleValue()));\n generateContentConfig.topK().ifPresent(topK -> requestBuilder.topK(topK.intValue()));\n generateContentConfig.maxOutputTokens().ifPresent(requestBuilder::maxOutputTokens);\n generateContentConfig.stopSequences().ifPresent(requestBuilder::stopSequences);\n generateContentConfig\n .frequencyPenalty()\n .ifPresent(freqPenalty -> requestBuilder.frequencyPenalty(freqPenalty.doubleValue()));\n generateContentConfig\n .presencePenalty()\n .ifPresent(presPenalty -> requestBuilder.presencePenalty(presPenalty.doubleValue()));\n\n if (generateContentConfig.toolConfig().isPresent()) {\n ToolConfig toolConfig = generateContentConfig.toolConfig().get();\n toolConfig\n .functionCallingConfig()\n .ifPresent(\n functionCallingConfig -> {\n functionCallingConfig\n .mode()\n .ifPresent(\n functionMode -> {\n if (functionMode\n .knownEnum()\n .equals(FunctionCallingConfigMode.Known.AUTO)) {\n requestBuilder.toolChoice(ToolChoice.AUTO);\n } else if (functionMode\n .knownEnum()\n .equals(FunctionCallingConfigMode.Known.ANY)) {\n // TODO check if it's the correct\n // mapping\n requestBuilder.toolChoice(ToolChoice.REQUIRED);\n functionCallingConfig\n .allowedFunctionNames()\n .ifPresent(\n allowedFunctionNames -> {\n requestBuilder.toolSpecifications(\n toolSpecifications.stream()\n .filter(\n toolSpecification ->\n allowedFunctionNames.contains(\n toolSpecification.name()))\n .toList());\n });\n } else if (functionMode\n .knownEnum()\n .equals(FunctionCallingConfigMode.Known.NONE)) {\n requestBuilder.toolSpecifications(List.of());\n }\n });\n });\n toolConfig\n .retrievalConfig()\n .ifPresent(\n retrievalConfig -> {\n // TODO? It exposes Latitude / Longitude, what to do with this?\n });\n }\n }\n\n return requestBuilder.messages(toMessages(llmRequest)).build();\n }\n\n private List toMessages(LlmRequest llmRequest) {\n List messages =\n new ArrayList<>(\n llmRequest.getSystemInstructions().stream().map(SystemMessage::from).toList());\n llmRequest.contents().forEach(content -> messages.addAll(toChatMessage(content)));\n return messages;\n }\n\n private List toChatMessage(Content content) {\n String role = content.role().orElseThrow().toLowerCase();\n return switch (role) {\n case \"user\" -> toUserOrToolResultMessage(content);\n case \"model\", \"assistant\" -> List.of(toAiMessage(content));\n default -> throw new IllegalStateException(\"Unexpected role: \" + role);\n };\n }\n\n private List toUserOrToolResultMessage(Content content) {\n List toolExecutionResultMessages = new ArrayList<>();\n List toolExecutionRequests = new ArrayList<>();\n\n List lc4jContents = new ArrayList<>();\n\n for (Part part : content.parts().orElse(List.of())) {\n if (part.text().isPresent()) {\n lc4jContents.add(TextContent.from(part.text().get()));\n } else if (part.functionResponse().isPresent()) {\n FunctionResponse functionResponse = part.functionResponse().get();\n toolExecutionResultMessages.add(\n ToolExecutionResultMessage.from(\n functionResponse.id().orElseThrow(),\n functionResponse.name().orElseThrow(),\n toJson(functionResponse.response().orElseThrow())));\n } else if (part.functionCall().isPresent()) {\n FunctionCall functionCall = part.functionCall().get();\n toolExecutionRequests.add(\n ToolExecutionRequest.builder()\n .id(functionCall.id().orElseThrow())\n .name(functionCall.name().orElseThrow())\n .arguments(toJson(functionCall.args().orElse(Map.of())))\n .build());\n } else if (part.inlineData().isPresent()) {\n Blob blob = part.inlineData().get();\n\n if (blob.mimeType().isEmpty() || blob.data().isEmpty()) {\n throw new IllegalArgumentException(\"Mime type and data required\");\n }\n\n byte[] bytes = blob.data().get();\n String mimeType = blob.mimeType().get();\n\n Base64.Encoder encoder = Base64.getEncoder();\n\n dev.langchain4j.data.message.Content lc4jContent = null;\n\n if (mimeType.startsWith(\"audio/\")) {\n lc4jContent =\n AudioContent.from(\n Audio.builder()\n .base64Data(encoder.encodeToString(bytes))\n .mimeType(mimeType)\n .build());\n } else if (mimeType.startsWith(\"video/\")) {\n lc4jContent =\n VideoContent.from(\n Video.builder()\n .base64Data(encoder.encodeToString(bytes))\n .mimeType(mimeType)\n .build());\n } else if (mimeType.startsWith(\"image/\")) {\n lc4jContent =\n ImageContent.from(\n Image.builder()\n .base64Data(encoder.encodeToString(bytes))\n .mimeType(mimeType)\n .build());\n } else if (mimeType.startsWith(\"application/pdf\")) {\n lc4jContent =\n PdfFileContent.from(\n PdfFile.builder()\n .base64Data(encoder.encodeToString(bytes))\n .mimeType(mimeType)\n .build());\n } else if (mimeType.startsWith(\"text/\")\n || mimeType.equals(\"application/json\")\n || mimeType.endsWith(\"+json\")\n || mimeType.endsWith(\"+xml\")) {\n // TODO are there missing text based mime types?\n // TODO should we assume UTF_8?\n lc4jContents.add(\n TextContent.from(new String(bytes, java.nio.charset.StandardCharsets.UTF_8)));\n }\n\n if (lc4jContent != null) {\n lc4jContents.add(lc4jContent);\n } else {\n throw new IllegalArgumentException(\"Unknown or unhandled mime type: \" + mimeType);\n }\n } else {\n throw new IllegalStateException(\n \"Text, media or functionCall is expected, but was: \" + part);\n }\n }\n\n if (!toolExecutionResultMessages.isEmpty()) {\n return new ArrayList(toolExecutionResultMessages);\n } else if (!toolExecutionRequests.isEmpty()) {\n return toolExecutionRequests.stream()\n .map(AiMessage::aiMessage)\n .map(msg -> (ChatMessage) msg)\n .toList();\n } else {\n return List.of(UserMessage.from(lc4jContents));\n }\n }\n\n private AiMessage toAiMessage(Content content) {\n List texts = new ArrayList<>();\n List toolExecutionRequests = new ArrayList<>();\n\n content\n .parts()\n .orElse(List.of())\n .forEach(\n part -> {\n if (part.text().isPresent()) {\n texts.add(part.text().get());\n } else if (part.functionCall().isPresent()) {\n FunctionCall functionCall = part.functionCall().get();\n ToolExecutionRequest toolExecutionRequest =\n ToolExecutionRequest.builder()\n .id(functionCall.id().orElseThrow())\n .name(functionCall.name().orElseThrow())\n .arguments(toJson(functionCall.args().orElseThrow()))\n .build();\n toolExecutionRequests.add(toolExecutionRequest);\n } else {\n throw new IllegalStateException(\n \"Either text or functionCall is expected, but was: \" + part);\n }\n });\n\n return AiMessage.builder()\n .text(String.join(\"\\n\", texts))\n .toolExecutionRequests(toolExecutionRequests)\n .build();\n }\n\n private String toJson(Object object) {\n try {\n return objectMapper.writeValueAsString(object);\n } catch (JsonProcessingException e) {\n throw new RuntimeException(e);\n }\n }\n\n private List toToolSpecifications(LlmRequest llmRequest) {\n List toolSpecifications = new ArrayList<>();\n\n llmRequest\n .tools()\n .values()\n .forEach(\n baseTool -> {\n if (baseTool.declaration().isPresent()) {\n FunctionDeclaration functionDeclaration = baseTool.declaration().get();\n if (functionDeclaration.parameters().isPresent()) {\n Schema schema = functionDeclaration.parameters().get();\n ToolSpecification toolSpecification =\n ToolSpecification.builder()\n .name(baseTool.name())\n .description(baseTool.description())\n .parameters(toParameters(schema))\n .build();\n toolSpecifications.add(toolSpecification);\n } else {\n // TODO exception or something else?\n throw new IllegalStateException(\"Tool lacking parameters: \" + baseTool);\n }\n } else {\n // TODO exception or something else?\n throw new IllegalStateException(\"Tool lacking declaration: \" + baseTool);\n }\n });\n\n return toolSpecifications;\n }\n\n private JsonObjectSchema toParameters(Schema schema) {\n if (schema.type().isPresent() && schema.type().get().knownEnum().equals(Type.Known.OBJECT)) {\n return JsonObjectSchema.builder()\n .addProperties(toProperties(schema))\n .required(schema.required().orElse(List.of()))\n .build();\n } else {\n throw new UnsupportedOperationException(\n \"LangChain4jLlm does not support schema of type: \" + schema.type());\n }\n }\n\n private Map toProperties(Schema schema) {\n Map properties = schema.properties().orElse(Map.of());\n Map result = new HashMap<>();\n properties.forEach((k, v) -> result.put(k, toJsonSchemaElement(v)));\n return result;\n }\n\n private JsonSchemaElement toJsonSchemaElement(Schema schema) {\n if (schema != null && schema.type().isPresent()) {\n Type type = schema.type().get();\n return switch (type.knownEnum()) {\n case STRING ->\n JsonStringSchema.builder().description(schema.description().orElse(null)).build();\n case NUMBER ->\n JsonNumberSchema.builder().description(schema.description().orElse(null)).build();\n case INTEGER ->\n JsonIntegerSchema.builder().description(schema.description().orElse(null)).build();\n case BOOLEAN ->\n JsonBooleanSchema.builder().description(schema.description().orElse(null)).build();\n case ARRAY ->\n JsonArraySchema.builder()\n .description(schema.description().orElse(null))\n .items(toJsonSchemaElement(schema.items().orElseThrow()))\n .build();\n case OBJECT -> toParameters(schema);\n case TYPE_UNSPECIFIED ->\n throw new UnsupportedFeatureException(\n \"LangChain4jLlm does not support schema of type: \" + type);\n };\n } else {\n throw new IllegalArgumentException(\"Schema type cannot be null or absent\");\n }\n }\n\n private LlmResponse toLlmResponse(ChatResponse chatResponse) {\n Content content =\n Content.builder().role(\"model\").parts(toParts(chatResponse.aiMessage())).build();\n\n return LlmResponse.builder().content(content).build();\n }\n\n private List toParts(AiMessage aiMessage) {\n if (aiMessage.hasToolExecutionRequests()) {\n List parts = new ArrayList<>();\n aiMessage\n .toolExecutionRequests()\n .forEach(\n toolExecutionRequest -> {\n FunctionCall functionCall =\n FunctionCall.builder()\n .id(\n toolExecutionRequest.id() != null\n ? toolExecutionRequest.id()\n : UUID.randomUUID().toString())\n .name(toolExecutionRequest.name())\n .args(toArgs(toolExecutionRequest))\n .build();\n Part part = Part.builder().functionCall(functionCall).build();\n parts.add(part);\n });\n return parts;\n } else {\n Part part = Part.builder().text(aiMessage.text()).build();\n return List.of(part);\n }\n }\n\n private Map toArgs(ToolExecutionRequest toolExecutionRequest) {\n try {\n return objectMapper.readValue(toolExecutionRequest.arguments(), MAP_TYPE_REFERENCE);\n } catch (JsonProcessingException e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public BaseLlmConnection connect(LlmRequest llmRequest) {\n throw new UnsupportedOperationException(\n \"Live connection is not supported for LangChain4j models.\");\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/mcp/McpTool.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools.mcp;\n\nimport static java.util.concurrent.TimeUnit.MILLISECONDS;\n\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.google.adk.JsonBaseModel;\nimport com.google.adk.tools.BaseTool;\nimport com.google.adk.tools.ToolContext;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.genai.types.FunctionDeclaration;\nimport com.google.genai.types.Schema;\nimport io.modelcontextprotocol.client.McpSyncClient;\nimport io.modelcontextprotocol.spec.McpSchema.CallToolRequest;\nimport io.modelcontextprotocol.spec.McpSchema.CallToolResult;\nimport io.modelcontextprotocol.spec.McpSchema.Content;\nimport io.modelcontextprotocol.spec.McpSchema.JsonSchema;\nimport io.modelcontextprotocol.spec.McpSchema.TextContent;\nimport io.modelcontextprotocol.spec.McpSchema.Tool;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\n\n// TODO(b/413489523): Add support for auth. This is a TODO for Python as well.\n/**\n * Initializes a MCP tool.\n *\n *

This wraps a MCP Tool interface and an active MCP Session. It invokes the MCP Tool through\n * executing the tool from remote MCP Session.\n */\npublic final class McpTool extends BaseTool {\n\n Tool mcpTool;\n McpSyncClient mcpSession;\n McpSessionManager mcpSessionManager;\n ObjectMapper objectMapper;\n\n /**\n * Creates a new McpTool with the default ObjectMapper.\n *\n * @param mcpTool The MCP tool to wrap.\n * @param mcpSession The MCP session to use to call the tool.\n * @param mcpSessionManager The MCP session manager to use to create new sessions.\n * @throws IllegalArgumentException If mcpTool or mcpSession are null.\n */\n public McpTool(Tool mcpTool, McpSyncClient mcpSession, McpSessionManager mcpSessionManager) {\n this(mcpTool, mcpSession, mcpSessionManager, JsonBaseModel.getMapper());\n }\n\n /**\n * Creates a new McpTool with the default ObjectMapper.\n *\n * @param mcpTool The MCP tool to wrap.\n * @param mcpSession The MCP session to use to call the tool.\n * @param mcpSessionManager The MCP session manager to use to create new sessions.\n * @param objectMapper The ObjectMapper to use to convert JSON schemas.\n * @throws IllegalArgumentException If mcpTool or mcpSession are null.\n */\n public McpTool(\n Tool mcpTool,\n McpSyncClient mcpSession,\n McpSessionManager mcpSessionManager,\n ObjectMapper objectMapper) {\n super(\n mcpTool == null ? \"\" : mcpTool.name(),\n mcpTool == null ? \"\" : (mcpTool.description().isEmpty() ? \"\" : mcpTool.description()));\n\n if (mcpTool == null) {\n throw new IllegalArgumentException(\"mcpTool cannot be null\");\n }\n if (mcpSession == null) {\n throw new IllegalArgumentException(\"mcpSession cannot be null\");\n }\n if (objectMapper == null) {\n throw new IllegalArgumentException(\"objectMapper cannot be null\");\n }\n this.mcpTool = mcpTool;\n this.mcpSession = mcpSession;\n this.mcpSessionManager = mcpSessionManager;\n this.objectMapper = objectMapper;\n }\n\n public Schema toGeminiSchema(JsonSchema openApiSchema) {\n return Schema.fromJson(objectMapper.valueToTree(openApiSchema).toString());\n }\n\n private void reintializeSession() {\n this.mcpSession = this.mcpSessionManager.createSession();\n }\n\n @Override\n public Optional declaration() {\n return Optional.of(\n FunctionDeclaration.builder()\n .name(this.name())\n .description(this.description())\n .parameters(toGeminiSchema(this.mcpTool.inputSchema()))\n .build());\n }\n\n @Override\n public Single> runAsync(Map args, ToolContext toolContext) {\n return Single.>fromCallable(\n () -> {\n CallToolResult callResult =\n mcpSession.callTool(new CallToolRequest(this.name(), ImmutableMap.copyOf(args)));\n\n if (callResult == null) {\n return ImmutableMap.of(\"error\", \"MCP framework error: CallToolResult was null\");\n }\n\n List contents = callResult.content();\n Boolean isToolError = callResult.isError();\n\n if (isToolError != null && isToolError) {\n String errorMessage = \"Tool execution failed.\";\n if (contents != null\n && !contents.isEmpty()\n && contents.get(0) instanceof TextContent) {\n TextContent textContent = (TextContent) contents.get(0);\n if (textContent.text() != null && !textContent.text().isEmpty()) {\n errorMessage += \" Details: \" + textContent.text();\n }\n }\n return ImmutableMap.of(\"error\", errorMessage);\n }\n\n if (contents == null || contents.isEmpty()) {\n return ImmutableMap.of();\n }\n\n List textOutputs = new ArrayList<>();\n for (Content content : contents) {\n if (content instanceof TextContent textContent) {\n if (textContent.text() != null) {\n textOutputs.add(textContent.text());\n }\n }\n }\n\n if (textOutputs.isEmpty()) {\n return ImmutableMap.of(\n \"error\",\n \"Tool '\" + this.name() + \"' returned content that is not TextContent.\",\n \"content_details\",\n contents.toString());\n }\n\n List> resultMaps = new ArrayList<>();\n for (String textOutput : textOutputs) {\n try {\n resultMaps.add(\n objectMapper.readValue(\n textOutput, new TypeReference>() {}));\n } catch (JsonProcessingException e) {\n resultMaps.add(ImmutableMap.of(\"text\", textOutput));\n }\n }\n return ImmutableMap.of(\"text_output\", resultMaps);\n })\n .retryWhen(\n errors ->\n errors\n .delay(100, MILLISECONDS)\n .take(3)\n .doOnNext(\n error -> {\n System.err.println(\"Retrying callTool due to: \" + error);\n reintializeSession();\n }));\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/models/Claude.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.models;\n\nimport com.anthropic.client.AnthropicClient;\nimport com.anthropic.models.messages.ContentBlock;\nimport com.anthropic.models.messages.ContentBlockParam;\nimport com.anthropic.models.messages.Message;\nimport com.anthropic.models.messages.MessageCreateParams;\nimport com.anthropic.models.messages.MessageParam;\nimport com.anthropic.models.messages.MessageParam.Role;\nimport com.anthropic.models.messages.TextBlockParam;\nimport com.anthropic.models.messages.Tool;\nimport com.anthropic.models.messages.ToolChoice;\nimport com.anthropic.models.messages.ToolChoiceAuto;\nimport com.anthropic.models.messages.ToolResultBlockParam;\nimport com.anthropic.models.messages.ToolUnion;\nimport com.anthropic.models.messages.ToolUseBlockParam;\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.fasterxml.jackson.datatype.jdk8.Jdk8Module;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.FunctionCall;\nimport com.google.genai.types.FunctionDeclaration;\nimport com.google.genai.types.GenerateContentConfig;\nimport com.google.genai.types.Part;\nimport io.reactivex.rxjava3.core.Flowable;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.Optional;\nimport java.util.stream.Collectors;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * Represents the Claude Generative AI model by Anthropic.\n *\n *

This class provides methods for interacting with Claude models. Streaming and live connections\n * are not currently supported for Claude.\n */\npublic class Claude extends BaseLlm {\n\n private static final Logger logger = LoggerFactory.getLogger(Claude.class);\n private static final int MAX_TOKEN = 8192;\n private final AnthropicClient anthropicClient;\n\n /**\n * Constructs a new Claude instance.\n *\n * @param modelName The name of the Claude model to use (e.g., \"claude-3-opus-20240229\").\n * @param anthropicClient The Anthropic API client instance.\n */\n public Claude(String modelName, AnthropicClient anthropicClient) {\n super(modelName);\n this.anthropicClient = anthropicClient;\n }\n\n @Override\n public Flowable generateContent(LlmRequest llmRequest, boolean stream) {\n // TODO: Switch to streaming API.\n List messages =\n llmRequest.contents().stream()\n .map(this::contentToAnthropicMessageParam)\n .collect(Collectors.toList());\n\n List tools = ImmutableList.of();\n if (llmRequest.config().isPresent()\n && llmRequest.config().get().tools().isPresent()\n && !llmRequest.config().get().tools().get().isEmpty()\n && llmRequest.config().get().tools().get().get(0).functionDeclarations().isPresent()) {\n tools =\n llmRequest.config().get().tools().get().get(0).functionDeclarations().get().stream()\n .map(this::functionDeclarationToAnthropicTool)\n .map(tool -> ToolUnion.ofTool(tool))\n .collect(Collectors.toList());\n }\n\n ToolChoice toolChoice =\n llmRequest.tools().isEmpty()\n ? null\n : ToolChoice.ofAuto(ToolChoiceAuto.builder().disableParallelToolUse(true).build());\n\n String systemText = \"\";\n Optional configOpt = llmRequest.config();\n if (configOpt.isPresent()) {\n Optional systemInstructionOpt = configOpt.get().systemInstruction();\n if (systemInstructionOpt.isPresent()) {\n String extractedSystemText =\n systemInstructionOpt.get().parts().orElse(ImmutableList.of()).stream()\n .filter(p -> p.text().isPresent())\n .map(p -> p.text().get())\n .collect(Collectors.joining(\"\\n\"));\n if (!extractedSystemText.isEmpty()) {\n systemText = extractedSystemText;\n }\n }\n }\n\n var message =\n this.anthropicClient\n .messages()\n .create(\n MessageCreateParams.builder()\n .model(llmRequest.model().orElse(model()))\n .system(systemText)\n .messages(messages)\n .tools(tools)\n .toolChoice(toolChoice)\n .maxTokens(MAX_TOKEN)\n .build());\n\n logger.debug(\"Claude response: {}\", message);\n\n return Flowable.just(convertAnthropicResponseToLlmResponse(message));\n }\n\n private Role toClaudeRole(String role) {\n return role.equals(\"model\") || role.equals(\"assistant\") ? Role.ASSISTANT : Role.USER;\n }\n\n private MessageParam contentToAnthropicMessageParam(Content content) {\n return MessageParam.builder()\n .role(toClaudeRole(content.role().orElse(\"\")))\n .contentOfBlockParams(\n content.parts().orElse(ImmutableList.of()).stream()\n .map(this::partToAnthropicMessageBlock)\n .filter(Objects::nonNull)\n .collect(Collectors.toList()))\n .build();\n }\n\n private ContentBlockParam partToAnthropicMessageBlock(Part part) {\n if (part.text().isPresent()) {\n return ContentBlockParam.ofText(TextBlockParam.builder().text(part.text().get()).build());\n } else if (part.functionCall().isPresent()) {\n return ContentBlockParam.ofToolUse(\n ToolUseBlockParam.builder()\n .id(part.functionCall().get().id().orElse(\"\"))\n .name(part.functionCall().get().name().orElseThrow())\n .type(com.anthropic.core.JsonValue.from(\"tool_use\"))\n .input(\n com.anthropic.core.JsonValue.from(\n part.functionCall().get().args().orElse(ImmutableMap.of())))\n .build());\n } else if (part.functionResponse().isPresent()) {\n String content = \"\";\n if (part.functionResponse().get().response().isPresent()\n && part.functionResponse().get().response().get().getOrDefault(\"result\", null) != null) {\n content = part.functionResponse().get().response().get().get(\"result\").toString();\n }\n return ContentBlockParam.ofToolResult(\n ToolResultBlockParam.builder()\n .toolUseId(part.functionResponse().get().id().orElse(\"\"))\n .content(content)\n .isError(false)\n .build());\n }\n throw new UnsupportedOperationException(\"Not supported yet.\");\n }\n\n private void updateTypeString(Map valueDict) {\n if (valueDict == null) {\n return;\n }\n if (valueDict.containsKey(\"type\")) {\n valueDict.put(\"type\", ((String) valueDict.get(\"type\")).toLowerCase());\n }\n\n if (valueDict.containsKey(\"items\")) {\n updateTypeString((Map) valueDict.get(\"items\"));\n\n if (valueDict.get(\"items\") instanceof Map\n && ((Map) valueDict.get(\"items\")).containsKey(\"properties\")) {\n Map properties =\n (Map) ((Map) valueDict.get(\"items\")).get(\"properties\");\n if (properties != null) {\n for (Object value : properties.values()) {\n if (value instanceof Map) {\n updateTypeString((Map) value);\n }\n }\n }\n }\n }\n }\n\n private Tool functionDeclarationToAnthropicTool(FunctionDeclaration functionDeclaration) {\n Map> properties = new HashMap<>();\n if (functionDeclaration.parameters().isPresent()\n && functionDeclaration.parameters().get().properties().isPresent()) {\n functionDeclaration\n .parameters()\n .get()\n .properties()\n .get()\n .forEach(\n (key, schema) -> {\n ObjectMapper objectMapper = new ObjectMapper();\n objectMapper.registerModule(new Jdk8Module());\n Map schemaMap =\n objectMapper.convertValue(schema, new TypeReference>() {});\n updateTypeString(schemaMap);\n properties.put(key, schemaMap);\n });\n }\n\n return Tool.builder()\n .name(functionDeclaration.name().orElseThrow())\n .description(functionDeclaration.description().orElse(\"\"))\n .inputSchema(\n Tool.InputSchema.builder()\n .properties(com.anthropic.core.JsonValue.from(properties))\n .build())\n .build();\n }\n\n private LlmResponse convertAnthropicResponseToLlmResponse(Message message) {\n LlmResponse.Builder responseBuilder = LlmResponse.builder();\n List parts = new ArrayList<>();\n\n if (message.content() != null) {\n for (ContentBlock block : message.content()) {\n Part part = anthropicContentBlockToPart(block);\n if (part != null) {\n parts.add(part);\n }\n }\n responseBuilder.content(\n Content.builder().role(\"model\").parts(ImmutableList.copyOf(parts)).build());\n }\n return responseBuilder.build();\n }\n\n private Part anthropicContentBlockToPart(ContentBlock block) {\n if (block.isText()) {\n return Part.builder().text(block.asText().text()).build();\n } else if (block.isToolUse()) {\n return Part.builder()\n .functionCall(\n FunctionCall.builder()\n .id(block.asToolUse().id())\n .name(block.asToolUse().name())\n .args(\n block\n .asToolUse()\n ._input()\n .convert(new TypeReference>() {}))\n .build())\n .build();\n }\n throw new UnsupportedOperationException(\"Not supported yet.\");\n }\n\n @Override\n public BaseLlmConnection connect(LlmRequest llmRequest) {\n throw new UnsupportedOperationException(\"Live connection is not supported for Claude models.\");\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/FunctionTool.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools;\n\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.genai.types.FunctionDeclaration;\nimport io.reactivex.rxjava3.core.Maybe;\nimport io.reactivex.rxjava3.core.Single;\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Modifier;\nimport java.lang.reflect.Parameter;\nimport java.lang.reflect.ParameterizedType;\nimport java.lang.reflect.Type;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\nimport javax.annotation.Nullable;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/** FunctionTool implements a customized function calling tool. */\npublic class FunctionTool extends BaseTool {\n private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();\n private static final Logger logger = LoggerFactory.getLogger(FunctionTool.class);\n\n @Nullable private final Object instance;\n private final Method func;\n private final FunctionDeclaration funcDeclaration;\n\n public static FunctionTool create(Object instance, Method func) {\n if (!areParametersAnnotatedWithSchema(func) && wasCompiledWithDefaultParameterNames(func)) {\n logger.error(\n \"Functions used in tools must have their parameters annotated with @Schema or at least\"\n + \" the code must be compiled with the -parameters flag as a fallback. Your function\"\n + \" tool will likely not work as expected and exit at runtime.\");\n }\n if (!Modifier.isStatic(func.getModifiers()) && !func.getDeclaringClass().isInstance(instance)) {\n throw new IllegalArgumentException(\n String.format(\n \"The instance provided is not an instance of the declaring class of the method.\"\n + \" Expected: %s, Actual: %s\",\n func.getDeclaringClass().getName(), instance.getClass().getName()));\n }\n return new FunctionTool(instance, func, /* isLongRunning= */ false);\n }\n\n public static FunctionTool create(Method func) {\n if (!areParametersAnnotatedWithSchema(func) && wasCompiledWithDefaultParameterNames(func)) {\n logger.error(\n \"Functions used in tools must have their parameters annotated with @Schema or at least\"\n + \" the code must be compiled with the -parameters flag as a fallback. Your function\"\n + \" tool will likely not work as expected and exit at runtime.\");\n }\n if (!Modifier.isStatic(func.getModifiers())) {\n throw new IllegalArgumentException(\"The method provided must be static.\");\n }\n return new FunctionTool(null, func, /* isLongRunning= */ false);\n }\n\n public static FunctionTool create(Class cls, String methodName) {\n for (Method method : cls.getMethods()) {\n if (method.getName().equals(methodName) && Modifier.isStatic(method.getModifiers())) {\n return create(null, method);\n }\n }\n throw new IllegalArgumentException(\n String.format(\"Static method %s not found in class %s.\", methodName, cls.getName()));\n }\n\n public static FunctionTool create(Object instance, String methodName) {\n Class cls = instance.getClass();\n for (Method method : cls.getMethods()) {\n if (method.getName().equals(methodName) && !Modifier.isStatic(method.getModifiers())) {\n return create(instance, method);\n }\n }\n throw new IllegalArgumentException(\n String.format(\"Instance method %s not found in class %s.\", methodName, cls.getName()));\n }\n\n private static boolean areParametersAnnotatedWithSchema(Method func) {\n for (Parameter parameter : func.getParameters()) {\n if (!parameter.isAnnotationPresent(Annotations.Schema.class)\n || parameter.getAnnotation(Annotations.Schema.class).name().isEmpty()) {\n return false;\n }\n }\n return true;\n }\n\n // Rough check to see if the code wasn't compiled with the -parameters flag.\n private static boolean wasCompiledWithDefaultParameterNames(Method func) {\n for (Parameter parameter : func.getParameters()) {\n String parameterName = parameter.getName();\n if (!parameterName.matches(\"arg\\\\d+\")) {\n return false;\n }\n }\n return true;\n }\n\n protected FunctionTool(@Nullable Object instance, Method func, boolean isLongRunning) {\n super(\n func.isAnnotationPresent(Annotations.Schema.class)\n && !func.getAnnotation(Annotations.Schema.class).name().isEmpty()\n ? func.getAnnotation(Annotations.Schema.class).name()\n : func.getName(),\n func.isAnnotationPresent(Annotations.Schema.class)\n ? func.getAnnotation(Annotations.Schema.class).description()\n : \"\",\n isLongRunning);\n boolean isStatic = Modifier.isStatic(func.getModifiers());\n if (isStatic && instance != null) {\n throw new IllegalArgumentException(\"Static function tool must not have an instance.\");\n } else if (!isStatic && instance == null) {\n throw new IllegalArgumentException(\"Instance function tool must have an instance.\");\n }\n\n this.instance = instance;\n this.func = func;\n this.funcDeclaration =\n FunctionCallingUtils.buildFunctionDeclaration(this.func, ImmutableList.of(\"toolContext\"));\n }\n\n @Override\n public Optional declaration() {\n return Optional.of(this.funcDeclaration);\n }\n\n @Override\n public Single> runAsync(Map args, ToolContext toolContext) {\n try {\n return this.call(args, toolContext).defaultIfEmpty(ImmutableMap.of());\n } catch (Exception e) {\n e.printStackTrace();\n return Single.just(ImmutableMap.of());\n }\n }\n\n @SuppressWarnings(\"unchecked\") // For tool parameter type casting.\n private Maybe> call(Map args, ToolContext toolContext)\n throws IllegalAccessException, InvocationTargetException {\n Parameter[] parameters = func.getParameters();\n Object[] arguments = new Object[parameters.length];\n for (int i = 0; i < parameters.length; i++) {\n String paramName =\n parameters[i].isAnnotationPresent(Annotations.Schema.class)\n && !parameters[i].getAnnotation(Annotations.Schema.class).name().isEmpty()\n ? parameters[i].getAnnotation(Annotations.Schema.class).name()\n : parameters[i].getName();\n if (paramName.equals(\"toolContext\")) {\n arguments[i] = toolContext;\n continue;\n }\n if (!args.containsKey(paramName)) {\n throw new IllegalArgumentException(\n String.format(\n \"The parameter '%s' was not found in the arguments provided by the model.\",\n paramName));\n }\n Class paramType = parameters[i].getType();\n Object argValue = args.get(paramName);\n if (paramType.equals(List.class)) {\n if (argValue instanceof List) {\n Type type =\n ((ParameterizedType) parameters[i].getParameterizedType())\n .getActualTypeArguments()[0];\n arguments[i] = createList((List) argValue, (Class) type);\n continue;\n }\n } else if (argValue instanceof Map) {\n arguments[i] = OBJECT_MAPPER.convertValue(argValue, paramType);\n continue;\n }\n arguments[i] = castValue(argValue, paramType);\n }\n Object result = func.invoke(instance, arguments);\n if (result == null) {\n return Maybe.empty();\n } else if (result instanceof Maybe) {\n return (Maybe>) result;\n } else if (result instanceof Single) {\n return ((Single>) result).toMaybe();\n } else {\n return Maybe.just((Map) result);\n }\n }\n\n private static List createList(List values, Class type) {\n List list = new ArrayList<>();\n // List of parameterized type is not supported.\n if (type == null) {\n return list;\n }\n Class cls = type;\n for (Object value : values) {\n if (cls == Integer.class\n || cls == Long.class\n || cls == Double.class\n || cls == Float.class\n || cls == Boolean.class\n || cls == String.class) {\n list.add(castValue(value, cls));\n } else {\n list.add(OBJECT_MAPPER.convertValue(value, type));\n }\n }\n return list;\n }\n\n private static Object castValue(Object value, Class type) {\n if (type.equals(Integer.class) || type.equals(int.class)) {\n if (value instanceof Integer) {\n return value;\n }\n }\n if (type.equals(Long.class) || type.equals(long.class)) {\n if (value instanceof Long || value instanceof Integer) {\n return value;\n }\n } else if (type.equals(Double.class) || type.equals(double.class)) {\n if (value instanceof Double d) {\n return d.doubleValue();\n }\n if (value instanceof Float f) {\n return f.doubleValue();\n }\n if (value instanceof Integer i) {\n return i.doubleValue();\n }\n if (value instanceof Long l) {\n return l.doubleValue();\n }\n } else if (type.equals(Float.class) || type.equals(float.class)) {\n if (value instanceof Double d) {\n return d.floatValue();\n }\n if (value instanceof Float f) {\n return f.floatValue();\n }\n if (value instanceof Integer i) {\n return i.floatValue();\n }\n if (value instanceof Long l) {\n return l.floatValue();\n }\n } else if (type.equals(Boolean.class) || type.equals(boolean.class)) {\n if (value instanceof Boolean) {\n return value;\n }\n } else if (type.equals(String.class)) {\n if (value instanceof String) {\n return value;\n }\n }\n return OBJECT_MAPPER.convertValue(value, type);\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/GoogleSearchTool.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools;\n\nimport com.google.adk.models.LlmRequest;\nimport com.google.common.collect.ImmutableList;\nimport com.google.genai.types.GenerateContentConfig;\nimport com.google.genai.types.GoogleSearch;\nimport com.google.genai.types.GoogleSearchRetrieval;\nimport com.google.genai.types.Tool;\nimport io.reactivex.rxjava3.core.Completable;\nimport java.util.List;\n\n/**\n * A built-in tool that is automatically invoked by Gemini 2 models to retrieve search results from\n * Google Search.\n *\n *

This tool operates internally within the model and does not require or perform local code\n * execution.\n */\npublic final class GoogleSearchTool extends BaseTool {\n\n public GoogleSearchTool() {\n super(\"google_search\", \"google_search\");\n }\n\n @Override\n public Completable processLlmRequest(\n LlmRequest.Builder llmRequestBuilder, ToolContext toolContext) {\n\n GenerateContentConfig.Builder configBuilder =\n llmRequestBuilder\n .build()\n .config()\n .map(GenerateContentConfig::toBuilder)\n .orElse(GenerateContentConfig.builder());\n\n List existingTools = configBuilder.build().tools().orElse(ImmutableList.of());\n ImmutableList.Builder updatedToolsBuilder = ImmutableList.builder();\n updatedToolsBuilder.addAll(existingTools);\n\n String model = llmRequestBuilder.build().model().get();\n if (model != null && model.startsWith(\"gemini-1\")) {\n if (!updatedToolsBuilder.build().isEmpty()) {\n System.out.println(configBuilder.build().tools().get());\n return Completable.error(\n new IllegalArgumentException(\n \"Google search tool cannot be used with other tools in Gemini 1.x.\"));\n }\n updatedToolsBuilder.add(\n Tool.builder().googleSearchRetrieval(GoogleSearchRetrieval.builder().build()).build());\n configBuilder.tools(updatedToolsBuilder.build());\n } else if (model != null && model.startsWith(\"gemini-2\")) {\n\n updatedToolsBuilder.add(Tool.builder().googleSearch(GoogleSearch.builder().build()).build());\n configBuilder.tools(updatedToolsBuilder.build());\n } else {\n return Completable.error(\n new IllegalArgumentException(\"Google search tool is not supported for model \" + model));\n }\n\n llmRequestBuilder.config(configBuilder.build());\n return Completable.complete();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/applicationintegrationtoolset/IntegrationConnectorTool.java", "package com.google.adk.tools.applicationintegrationtoolset;\n\nimport static com.google.common.base.Strings.isNullOrEmpty;\nimport static java.nio.charset.StandardCharsets.UTF_8;\n\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.fasterxml.jackson.databind.node.ArrayNode;\nimport com.fasterxml.jackson.databind.node.ObjectNode;\nimport com.google.adk.tools.BaseTool;\nimport com.google.adk.tools.ToolContext;\nimport com.google.auth.oauth2.GoogleCredentials;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Streams;\nimport com.google.genai.types.FunctionDeclaration;\nimport com.google.genai.types.Schema;\nimport io.reactivex.rxjava3.core.Single;\nimport java.io.ByteArrayInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\nimport org.jspecify.annotations.Nullable;\n\n/** Application Integration Tool */\npublic class IntegrationConnectorTool extends BaseTool {\n\n private final String openApiSpec;\n private final String pathUrl;\n private final HttpExecutor httpExecutor;\n private final String connectionName;\n private final String serviceName;\n private final String host;\n private String entity;\n private String operation;\n private String action;\n private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();\n\n interface HttpExecutor {\n HttpResponse send(HttpRequest request, HttpResponse.BodyHandler responseBodyHandler)\n throws IOException, InterruptedException;\n\n String getToken() throws IOException;\n\n public HttpExecutor createExecutor(String serviceAccountJson);\n }\n\n static class DefaultHttpExecutor implements HttpExecutor {\n private final HttpClient client = HttpClient.newHttpClient();\n private final String serviceAccountJson;\n\n /** Default constructor for when no service account is specified. */\n DefaultHttpExecutor() {\n this(null);\n }\n\n /**\n * Constructor that accepts an optional service account JSON string.\n *\n * @param serviceAccountJson The service account key as a JSON string, or null.\n */\n DefaultHttpExecutor(@Nullable String serviceAccountJson) {\n this.serviceAccountJson = serviceAccountJson;\n }\n\n @Override\n public HttpResponse send(\n HttpRequest request, HttpResponse.BodyHandler responseBodyHandler)\n throws IOException, InterruptedException {\n return client.send(request, responseBodyHandler);\n }\n\n @Override\n public String getToken() throws IOException {\n GoogleCredentials credentials;\n\n if (this.serviceAccountJson != null && !this.serviceAccountJson.trim().isEmpty()) {\n try (InputStream is = new ByteArrayInputStream(this.serviceAccountJson.getBytes(UTF_8))) {\n credentials =\n GoogleCredentials.fromStream(is)\n .createScoped(\"https://www.googleapis.com/auth/cloud-platform\");\n } catch (IOException e) {\n throw new IOException(\"Failed to load credentials from service_account_json.\", e);\n }\n } else {\n try {\n credentials =\n GoogleCredentials.getApplicationDefault()\n .createScoped(\"https://www.googleapis.com/auth/cloud-platform\");\n } catch (IOException e) {\n throw new IOException(\n \"Please provide a service account or configure Application Default Credentials. To\"\n + \" set up ADC, see\"\n + \" https://cloud.google.com/docs/authentication/external/set-up-adc.\",\n e);\n }\n }\n\n credentials.refreshIfExpired();\n return credentials.getAccessToken().getTokenValue();\n }\n\n @Override\n public HttpExecutor createExecutor(String serviceAccountJson) {\n if (isNullOrEmpty(serviceAccountJson)) {\n return new DefaultHttpExecutor();\n } else {\n return new DefaultHttpExecutor(serviceAccountJson);\n }\n }\n }\n\n private static final ImmutableList EXCLUDE_FIELDS =\n ImmutableList.of(\"connectionName\", \"serviceName\", \"host\", \"entity\", \"operation\", \"action\");\n\n private static final ImmutableList OPTIONAL_FIELDS =\n ImmutableList.of(\"pageSize\", \"pageToken\", \"filter\", \"sortByColumns\");\n\n /** Constructor for Application Integration Tool for integration */\n IntegrationConnectorTool(\n String openApiSpec,\n String pathUrl,\n String toolName,\n String toolDescription,\n String serviceAccountJson) {\n this(\n openApiSpec,\n pathUrl,\n toolName,\n toolDescription,\n null,\n null,\n null,\n serviceAccountJson,\n new DefaultHttpExecutor().createExecutor(serviceAccountJson));\n }\n\n /**\n * Constructor for Application Integration Tool with connection name, service name, host, entity,\n * operation, and action\n */\n IntegrationConnectorTool(\n String openApiSpec,\n String pathUrl,\n String toolName,\n String toolDescription,\n String connectionName,\n String serviceName,\n String host,\n String serviceAccountJson) {\n this(\n openApiSpec,\n pathUrl,\n toolName,\n toolDescription,\n connectionName,\n serviceName,\n host,\n serviceAccountJson,\n new DefaultHttpExecutor().createExecutor(serviceAccountJson));\n }\n\n IntegrationConnectorTool(\n String openApiSpec,\n String pathUrl,\n String toolName,\n String toolDescription,\n @Nullable String connectionName,\n @Nullable String serviceName,\n @Nullable String host,\n @Nullable String serviceAccountJson,\n HttpExecutor httpExecutor) {\n super(toolName, toolDescription);\n this.openApiSpec = openApiSpec;\n this.pathUrl = pathUrl;\n this.connectionName = connectionName;\n this.serviceName = serviceName;\n this.host = host;\n this.httpExecutor = httpExecutor;\n }\n\n Schema toGeminiSchema(String openApiSchema, String operationId) throws Exception {\n String resolvedSchemaString = getResolvedRequestSchemaByOperationId(openApiSchema, operationId);\n return Schema.fromJson(resolvedSchemaString);\n }\n\n @Override\n public Optional declaration() {\n try {\n String operationId = getOperationIdFromPathUrl(openApiSpec, pathUrl);\n Schema parametersSchema = toGeminiSchema(openApiSpec, operationId);\n String operationDescription = getOperationDescription(openApiSpec, operationId);\n\n FunctionDeclaration declaration =\n FunctionDeclaration.builder()\n .name(operationId)\n .description(operationDescription)\n .parameters(parametersSchema)\n .build();\n return Optional.of(declaration);\n } catch (Exception e) {\n System.err.println(\"Failed to get OpenAPI spec: \" + e.getMessage());\n return Optional.empty();\n }\n }\n\n @Override\n public Single> runAsync(Map args, ToolContext toolContext) {\n if (this.connectionName != null) {\n args.put(\"connectionName\", this.connectionName);\n args.put(\"serviceName\", this.serviceName);\n args.put(\"host\", this.host);\n if (!isNullOrEmpty(this.entity)) {\n args.put(\"entity\", this.entity);\n } else if (!isNullOrEmpty(this.action)) {\n args.put(\"action\", this.action);\n }\n if (!isNullOrEmpty(this.operation)) {\n args.put(\"operation\", this.operation);\n }\n }\n\n return Single.fromCallable(\n () -> {\n try {\n String response = executeIntegration(args);\n return ImmutableMap.of(\"result\", response);\n } catch (Exception e) {\n System.err.println(\"Failed to execute integration: \" + e.getMessage());\n return ImmutableMap.of(\"error\", e.getMessage());\n }\n });\n }\n\n private String executeIntegration(Map args) throws Exception {\n String url = String.format(\"https://integrations.googleapis.com%s\", this.pathUrl);\n String jsonRequestBody;\n try {\n jsonRequestBody = OBJECT_MAPPER.writeValueAsString(args);\n } catch (IOException e) {\n throw new Exception(\"Error converting args to JSON: \" + e.getMessage(), e);\n }\n HttpRequest request =\n HttpRequest.newBuilder()\n .uri(URI.create(url))\n .header(\"Authorization\", \"Bearer \" + httpExecutor.getToken())\n .header(\"Content-Type\", \"application/json\")\n .POST(HttpRequest.BodyPublishers.ofString(jsonRequestBody))\n .build();\n HttpResponse response =\n httpExecutor.send(request, HttpResponse.BodyHandlers.ofString());\n\n if (response.statusCode() < 200 || response.statusCode() >= 300) {\n throw new Exception(\n \"Error executing integration. Status: \"\n + response.statusCode()\n + \" , Response: \"\n + response.body());\n }\n return response.body();\n }\n\n String getOperationIdFromPathUrl(String openApiSchemaString, String pathUrl) throws Exception {\n JsonNode topLevelNode = OBJECT_MAPPER.readTree(openApiSchemaString);\n JsonNode specNode = topLevelNode.path(\"openApiSpec\");\n if (specNode.isMissingNode() || !specNode.isTextual()) {\n throw new IllegalArgumentException(\n \"Failed to get OpenApiSpec, please check the project and region for the integration.\");\n }\n JsonNode rootNode = OBJECT_MAPPER.readTree(specNode.asText());\n JsonNode paths = rootNode.path(\"paths\");\n\n // Iterate through each path in the OpenAPI spec.\n Iterator> pathsFields = paths.fields();\n while (pathsFields.hasNext()) {\n Map.Entry pathEntry = pathsFields.next();\n String currentPath = pathEntry.getKey();\n if (!currentPath.equals(pathUrl)) {\n continue;\n }\n JsonNode pathItem = pathEntry.getValue();\n\n Iterator> methods = pathItem.fields();\n while (methods.hasNext()) {\n Map.Entry methodEntry = methods.next();\n JsonNode operationNode = methodEntry.getValue();\n // Set values for entity, operation, and action\n this.entity = \"\";\n this.operation = \"\";\n this.action = \"\";\n if (operationNode.has(\"x-entity\")) {\n this.entity = operationNode.path(\"x-entity\").asText();\n } else if (operationNode.has(\"x-action\")) {\n this.action = operationNode.path(\"x-action\").asText();\n }\n if (operationNode.has(\"x-operation\")) {\n this.operation = operationNode.path(\"x-operation\").asText();\n }\n // Get the operationId from the operationNode\n if (operationNode.has(\"operationId\")) {\n return operationNode.path(\"operationId\").asText();\n }\n }\n }\n throw new Exception(\"Could not find operationId for pathUrl: \" + pathUrl);\n }\n\n private String getResolvedRequestSchemaByOperationId(\n String openApiSchemaString, String operationId) throws Exception {\n JsonNode topLevelNode = OBJECT_MAPPER.readTree(openApiSchemaString);\n JsonNode specNode = topLevelNode.path(\"openApiSpec\");\n if (specNode.isMissingNode() || !specNode.isTextual()) {\n throw new IllegalArgumentException(\n \"Failed to get OpenApiSpec, please check the project and region for the integration.\");\n }\n JsonNode rootNode = OBJECT_MAPPER.readTree(specNode.asText());\n JsonNode operationNode = findOperationNodeById(rootNode, operationId);\n if (operationNode == null) {\n throw new Exception(\"Could not find operation with operationId: \" + operationId);\n }\n JsonNode requestSchemaNode =\n operationNode.path(\"requestBody\").path(\"content\").path(\"application/json\").path(\"schema\");\n\n if (requestSchemaNode.isMissingNode()) {\n throw new Exception(\"Could not find request body schema for operationId: \" + operationId);\n }\n\n JsonNode resolvedSchema = resolveRefs(requestSchemaNode, rootNode);\n\n if (resolvedSchema.isObject()) {\n ObjectNode schemaObject = (ObjectNode) resolvedSchema;\n\n // 1. Remove excluded fields from the 'properties' object.\n JsonNode propertiesNode = schemaObject.path(\"properties\");\n if (propertiesNode.isObject()) {\n ObjectNode propertiesObject = (ObjectNode) propertiesNode;\n for (String field : EXCLUDE_FIELDS) {\n propertiesObject.remove(field);\n }\n }\n\n // 2. Remove optional and excluded fields from the 'required' array.\n JsonNode requiredNode = schemaObject.path(\"required\");\n if (requiredNode.isArray()) {\n // Combine the lists of fields to remove\n List fieldsToRemove =\n Streams.concat(OPTIONAL_FIELDS.stream(), EXCLUDE_FIELDS.stream()).toList();\n\n // To safely remove items from a list while iterating, we must use an Iterator.\n ArrayNode requiredArray = (ArrayNode) requiredNode;\n Iterator elements = requiredArray.elements();\n while (elements.hasNext()) {\n JsonNode element = elements.next();\n if (element.isTextual() && fieldsToRemove.contains(element.asText())) {\n // This removes the current element from the underlying array.\n elements.remove();\n }\n }\n }\n }\n return OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(resolvedSchema);\n }\n\n private @Nullable JsonNode findOperationNodeById(JsonNode rootNode, String operationId) {\n JsonNode paths = rootNode.path(\"paths\");\n for (JsonNode pathItem : paths) {\n Iterator> methods = pathItem.fields();\n while (methods.hasNext()) {\n Map.Entry methodEntry = methods.next();\n JsonNode operationNode = methodEntry.getValue();\n if (operationNode.path(\"operationId\").asText().equals(operationId)) {\n return operationNode;\n }\n }\n }\n return null;\n }\n\n private JsonNode resolveRefs(JsonNode currentNode, JsonNode rootNode) {\n if (currentNode.isObject()) {\n ObjectNode objectNode = (ObjectNode) currentNode;\n if (objectNode.has(\"$ref\")) {\n String refPath = objectNode.get(\"$ref\").asText();\n if (refPath.isEmpty() || !refPath.startsWith(\"#/\")) {\n return objectNode;\n }\n JsonNode referencedNode = rootNode.at(refPath.substring(1));\n if (referencedNode.isMissingNode()) {\n return objectNode;\n }\n return resolveRefs(referencedNode, rootNode);\n } else {\n ObjectNode newObjectNode = OBJECT_MAPPER.createObjectNode();\n Iterator> fields = currentNode.fields();\n while (fields.hasNext()) {\n Map.Entry field = fields.next();\n newObjectNode.set(field.getKey(), resolveRefs(field.getValue(), rootNode));\n }\n return newObjectNode;\n }\n }\n return currentNode;\n }\n\n private String getOperationDescription(String openApiSchemaString, String operationId)\n throws Exception {\n JsonNode topLevelNode = OBJECT_MAPPER.readTree(openApiSchemaString);\n JsonNode specNode = topLevelNode.path(\"openApiSpec\");\n if (specNode.isMissingNode() || !specNode.isTextual()) {\n return \"\";\n }\n JsonNode rootNode = OBJECT_MAPPER.readTree(specNode.asText());\n JsonNode operationNode = findOperationNodeById(rootNode, operationId);\n if (operationNode == null) {\n return \"\";\n }\n return operationNode.path(\"summary\").asText();\n }\n}\n"], ["/adk-java/dev/src/main/java/com/google/adk/web/AgentGraphGenerator.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.web;\n\nimport com.google.adk.agents.BaseAgent;\nimport com.google.adk.agents.LlmAgent;\nimport com.google.adk.tools.AgentTool;\nimport com.google.adk.tools.BaseTool;\nimport com.google.adk.tools.FunctionTool;\nimport com.google.adk.tools.retrieval.BaseRetrievalTool;\nimport guru.nidi.graphviz.attribute.Arrow;\nimport guru.nidi.graphviz.attribute.Color;\nimport guru.nidi.graphviz.attribute.Label;\nimport guru.nidi.graphviz.attribute.Rank;\nimport guru.nidi.graphviz.attribute.Shape;\nimport guru.nidi.graphviz.attribute.Style;\nimport guru.nidi.graphviz.engine.Format;\nimport guru.nidi.graphviz.engine.Graphviz;\nimport guru.nidi.graphviz.model.Factory;\nimport guru.nidi.graphviz.model.Link;\nimport guru.nidi.graphviz.model.MutableGraph;\nimport guru.nidi.graphviz.model.MutableNode;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.Set;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/** Utility class to generate Graphviz DOT representations of Agent structures. */\npublic class AgentGraphGenerator {\n\n private static final Logger log = LoggerFactory.getLogger(AgentGraphGenerator.class);\n\n private static final Color DARK_GREEN = Color.rgb(\"#0F5223\");\n private static final Color LIGHT_GREEN = Color.rgb(\"#69CB87\");\n private static final Color LIGHT_GRAY = Color.rgb(\"#CCCCCC\");\n private static final Color BG_COLOR = Color.rgb(\"#333537\");\n\n /**\n * Generates the DOT source string for the agent graph.\n *\n * @param rootAgent The root agent of the structure.\n * @param highlightPairs A list where each inner list contains two strings (fromNode, toNode)\n * representing an edge to highlight. Order matters for direction.\n * @return The DOT source string, or null if graph generation fails.\n */\n public static Optional getAgentGraphDotSource(\n BaseAgent rootAgent, List> highlightPairs) {\n log.debug(\n \"Building agent graph with root: {}, highlights: {}\", rootAgent.name(), highlightPairs);\n try {\n MutableGraph graph =\n Factory.mutGraph(\"AgentGraph\")\n .setDirected(true)\n .graphAttrs()\n .add(Rank.dir(Rank.RankDir.LEFT_TO_RIGHT), BG_COLOR.background());\n\n Set visitedNodes = new HashSet<>();\n buildGraphRecursive(graph, rootAgent, highlightPairs, visitedNodes);\n\n String dotSource = Graphviz.fromGraph(graph).render(Format.DOT).toString();\n log.debug(\"Generated DOT source successfully.\");\n return Optional.of(dotSource);\n } catch (Exception e) {\n log.error(\"Error generating agent graph DOT source\", e);\n return Optional.empty();\n }\n }\n\n /** Recursively builds the graph structure. */\n private static void buildGraphRecursive(\n MutableGraph graph,\n BaseAgent agent,\n List> highlightPairs,\n Set visitedNodes) {\n if (agent == null || visitedNodes.contains(getNodeName(agent))) {\n return;\n }\n\n drawNode(graph, agent, highlightPairs, visitedNodes);\n\n if (agent.subAgents() != null) {\n for (BaseAgent subAgent : agent.subAgents()) {\n if (subAgent != null) {\n drawEdge(graph, getNodeName(agent), getNodeName(subAgent), highlightPairs);\n buildGraphRecursive(graph, subAgent, highlightPairs, visitedNodes);\n }\n }\n }\n\n if (agent instanceof LlmAgent) {\n LlmAgent llmAgent = (LlmAgent) agent;\n List tools = llmAgent.canonicalTools().toList().blockingGet();\n if (tools != null) {\n for (BaseTool tool : tools) {\n if (tool != null) {\n drawNode(graph, tool, highlightPairs, visitedNodes);\n drawEdge(graph, getNodeName(agent), getNodeName(tool), highlightPairs);\n }\n }\n }\n }\n }\n\n /** Draws a node for an agent or tool, applying highlighting if applicable. */\n private static void drawNode(\n MutableGraph graph,\n Object toolOrAgent,\n List> highlightPairs,\n Set visitedNodes) {\n String name = getNodeName(toolOrAgent);\n if (name == null || name.isEmpty() || visitedNodes.contains(name)) {\n return;\n }\n\n Shape shape = getNodeShape(toolOrAgent);\n String caption = getNodeCaption(toolOrAgent);\n boolean isHighlighted = isNodeHighlighted(name, highlightPairs);\n\n MutableNode node =\n Factory.mutNode(name).add(Label.of(caption)).add(shape).add(LIGHT_GRAY.font());\n if (isHighlighted) {\n node.add(Style.FILLED);\n node.add(DARK_GREEN);\n } else {\n node.add(Style.ROUNDED);\n node.add(LIGHT_GRAY);\n }\n graph.add(node);\n visitedNodes.add(name);\n log.trace(\n \"Added node: name={}, caption={}, shape={}, highlighted={}\",\n name,\n caption,\n shape,\n isHighlighted);\n }\n\n /** Draws an edge between two nodes, applying highlighting if applicable. */\n private static void drawEdge(\n MutableGraph graph, String fromName, String toName, List> highlightPairs) {\n if (fromName == null || fromName.isEmpty() || toName == null || toName.isEmpty()) {\n log.warn(\n \"Skipping edge draw due to null or empty name: from='{}', to='{}'\", fromName, toName);\n return;\n }\n\n Optional highlightForward = isEdgeHighlighted(fromName, toName, highlightPairs);\n Link link = Factory.to(Factory.mutNode(toName));\n\n if (highlightForward.isPresent()) {\n link = link.with(LIGHT_GREEN);\n if (!highlightForward.get()) { // If true, means b->a was highlighted, draw reverse arrow\n link = link.with(Arrow.NORMAL.dir(Arrow.DirType.BACK));\n } else {\n link = link.with(Arrow.NORMAL);\n }\n } else {\n link = link.with(LIGHT_GRAY, Arrow.NONE);\n }\n\n graph.add(Factory.mutNode(fromName).addLink(link));\n log.trace(\n \"Added edge: from={}, to={}, highlighted={}\",\n fromName,\n toName,\n highlightForward.isPresent());\n }\n\n private static String getNodeName(Object toolOrAgent) {\n if (toolOrAgent instanceof BaseAgent) {\n return ((BaseAgent) toolOrAgent).name();\n } else if (toolOrAgent instanceof BaseTool) {\n return ((BaseTool) toolOrAgent).name();\n } else {\n log.warn(\"Unsupported type for getNodeName: {}\", toolOrAgent.getClass().getName());\n return \"unknown_\" + toolOrAgent.hashCode();\n }\n }\n\n private static String getNodeCaption(Object toolOrAgent) {\n String name = getNodeName(toolOrAgent); // Get name first\n if (toolOrAgent instanceof BaseAgent) {\n return \"🤖 \" + name;\n } else if (toolOrAgent instanceof BaseRetrievalTool) {\n return \"🔎 \" + name;\n } else if (toolOrAgent instanceof FunctionTool) {\n return \"🔧 \" + name;\n } else if (toolOrAgent instanceof AgentTool) {\n return \"🤖 \" + name;\n } else if (toolOrAgent instanceof BaseTool) {\n return \"🔧 \" + name;\n } else {\n log.warn(\"Unsupported type for getNodeCaption: {}\", toolOrAgent.getClass().getName());\n return \"❓ \" + name;\n }\n }\n\n private static Shape getNodeShape(Object toolOrAgent) {\n if (toolOrAgent instanceof BaseAgent) {\n return Shape.ELLIPSE;\n } else if (toolOrAgent instanceof BaseRetrievalTool) {\n return Shape.CYLINDER;\n } else if (toolOrAgent instanceof FunctionTool) {\n return Shape.BOX;\n } else if (toolOrAgent instanceof BaseTool) {\n return Shape.BOX;\n } else {\n log.warn(\"Unsupported type for getNodeShape: {}\", toolOrAgent.getClass().getName());\n return Shape.EGG;\n }\n }\n\n private static boolean isNodeHighlighted(String nodeName, List> highlightPairs) {\n if (highlightPairs == null || nodeName == null) {\n return false;\n }\n for (List pair : highlightPairs) {\n if (pair != null && pair.contains(nodeName)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Checks if an edge should be highlighted. Returns Optional: empty=no, true=forward,\n * false=backward\n */\n private static Optional isEdgeHighlighted(\n String fromName, String toName, List> highlightPairs) {\n if (highlightPairs == null || fromName == null || toName == null) {\n return Optional.empty();\n }\n for (List pair : highlightPairs) {\n if (pair != null && pair.size() == 2) {\n String pairFrom = pair.get(0);\n String pairTo = pair.get(1);\n if (fromName.equals(pairFrom) && toName.equals(pairTo)) {\n return Optional.of(true);\n }\n if (fromName.equals(pairTo) && toName.equals(pairFrom)) {\n return Optional.of(false);\n }\n }\n }\n return Optional.empty();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/llmflows/Functions.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows.llmflows;\n\nimport com.google.adk.Telemetry;\nimport com.google.adk.agents.Callbacks.AfterToolCallback;\nimport com.google.adk.agents.Callbacks.BeforeToolCallback;\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.agents.LlmAgent;\nimport com.google.adk.events.Event;\nimport com.google.adk.events.EventActions;\nimport com.google.adk.tools.BaseTool;\nimport com.google.adk.tools.ToolContext;\nimport com.google.common.base.VerifyException;\nimport com.google.common.collect.ImmutableList;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.FunctionCall;\nimport com.google.genai.types.FunctionResponse;\nimport com.google.genai.types.Part;\nimport io.opentelemetry.api.trace.Span;\nimport io.opentelemetry.api.trace.Tracer;\nimport io.opentelemetry.context.Scope;\nimport io.reactivex.rxjava3.core.Flowable;\nimport io.reactivex.rxjava3.core.Maybe;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.Set;\nimport java.util.UUID;\nimport org.jspecify.annotations.Nullable;\n\n/** Utility class for handling function calls. */\npublic final class Functions {\n\n private static final String AF_FUNCTION_CALL_ID_PREFIX = \"adk-\";\n\n /** Generates a unique ID for a function call. */\n public static String generateClientFunctionCallId() {\n return AF_FUNCTION_CALL_ID_PREFIX + UUID.randomUUID();\n }\n\n /**\n * Populates missing function call IDs in the provided event's content.\n *\n *

If the event contains function calls without an ID, this method generates a unique\n * client-side ID for each and updates the event content.\n *\n * @param modelResponseEvent The event potentially containing function calls.\n */\n public static void populateClientFunctionCallId(Event modelResponseEvent) {\n Optional originalContentOptional = modelResponseEvent.content();\n if (originalContentOptional.isEmpty()) {\n return;\n }\n Content originalContent = originalContentOptional.get();\n List originalParts = originalContent.parts().orElse(ImmutableList.of());\n if (originalParts.stream().noneMatch(part -> part.functionCall().isPresent())) {\n return; // No function calls to process\n }\n\n List newParts = new ArrayList<>();\n boolean modified = false;\n for (Part part : originalParts) {\n if (part.functionCall().isPresent()) {\n FunctionCall functionCall = part.functionCall().get();\n if (functionCall.id().isEmpty() || functionCall.id().get().isEmpty()) {\n FunctionCall updatedFunctionCall =\n functionCall.toBuilder().id(generateClientFunctionCallId()).build();\n newParts.add(Part.builder().functionCall(updatedFunctionCall).build());\n modified = true;\n } else {\n newParts.add(part); // Keep original part if ID exists\n }\n } else {\n newParts.add(part); // Keep non-function call parts\n }\n }\n\n if (modified) {\n String role =\n originalContent\n .role()\n .orElseThrow(\n () ->\n new IllegalStateException(\n \"Content role is missing in event: \" + modelResponseEvent.id()));\n Content newContent = Content.builder().role(role).parts(newParts).build();\n modelResponseEvent.setContent(Optional.of(newContent));\n }\n }\n\n // TODO - b/413761119 add the remaining methods for function call id.\n\n public static Maybe handleFunctionCalls(\n InvocationContext invocationContext, Event functionCallEvent, Map tools) {\n ImmutableList functionCalls = functionCallEvent.functionCalls();\n\n List> functionResponseEvents = new ArrayList<>();\n\n for (FunctionCall functionCall : functionCalls) {\n if (!tools.containsKey(functionCall.name().get())) {\n throw new VerifyException(\"Tool not found: \" + functionCall.name().get());\n }\n BaseTool tool = tools.get(functionCall.name().get());\n ToolContext toolContext =\n ToolContext.builder(invocationContext)\n .functionCallId(functionCall.id().orElse(\"\"))\n .build();\n\n Map functionArgs = functionCall.args().orElse(new HashMap<>());\n\n Maybe> maybeFunctionResult =\n maybeInvokeBeforeToolCall(invocationContext, tool, functionArgs, toolContext)\n .switchIfEmpty(Maybe.defer(() -> callTool(tool, functionArgs, toolContext)));\n\n Maybe maybeFunctionResponseEvent =\n maybeFunctionResult\n .map(Optional::of)\n .defaultIfEmpty(Optional.empty())\n .flatMapMaybe(\n optionalInitialResult -> {\n Map initialFunctionResult = optionalInitialResult.orElse(null);\n\n Maybe> afterToolResultMaybe =\n maybeInvokeAfterToolCall(\n invocationContext,\n tool,\n functionArgs,\n toolContext,\n initialFunctionResult);\n\n return afterToolResultMaybe\n .map(Optional::of)\n .defaultIfEmpty(Optional.ofNullable(initialFunctionResult))\n .flatMapMaybe(\n finalOptionalResult -> {\n Map finalFunctionResult =\n finalOptionalResult.orElse(null);\n if (tool.longRunning() && finalFunctionResult == null) {\n return Maybe.empty();\n }\n Event functionResponseEvent =\n buildResponseEvent(\n tool, finalFunctionResult, toolContext, invocationContext);\n return Maybe.just(functionResponseEvent);\n });\n });\n\n functionResponseEvents.add(maybeFunctionResponseEvent);\n }\n\n return Maybe.merge(functionResponseEvents)\n .toList()\n .flatMapMaybe(\n events -> {\n if (events.isEmpty()) {\n return Maybe.empty();\n }\n Event mergedEvent = Functions.mergeParallelFunctionResponseEvents(events);\n if (mergedEvent == null) {\n return Maybe.empty();\n }\n\n if (events.size() > 1) {\n Tracer tracer = Telemetry.getTracer();\n Span mergedSpan = tracer.spanBuilder(\"tool_response\").startSpan();\n try (Scope scope = mergedSpan.makeCurrent()) {\n Telemetry.traceToolResponse(invocationContext, mergedEvent.id(), mergedEvent);\n } finally {\n mergedSpan.end();\n }\n }\n return Maybe.just(mergedEvent);\n });\n }\n\n public static Set getLongRunningFunctionCalls(\n List functionCalls, Map tools) {\n Set longRunningFunctionCalls = new HashSet<>();\n for (FunctionCall functionCall : functionCalls) {\n if (!tools.containsKey(functionCall.name().get())) {\n continue;\n }\n BaseTool tool = tools.get(functionCall.name().get());\n if (tool.longRunning()) {\n longRunningFunctionCalls.add(functionCall.id().orElse(\"\"));\n }\n }\n return longRunningFunctionCalls;\n }\n\n private static @Nullable Event mergeParallelFunctionResponseEvents(\n List functionResponseEvents) {\n if (functionResponseEvents.isEmpty()) {\n return null;\n }\n if (functionResponseEvents.size() == 1) {\n return functionResponseEvents.get(0);\n }\n // Use the first event as the base for common attributes\n Event baseEvent = functionResponseEvents.get(0);\n\n List mergedParts = new ArrayList<>();\n for (Event event : functionResponseEvents) {\n event.content().flatMap(Content::parts).ifPresent(mergedParts::addAll);\n }\n\n // Merge actions from all events\n // TODO: validate that pending actions are not cleared away\n EventActions.Builder mergedActionsBuilder = EventActions.builder();\n for (Event event : functionResponseEvents) {\n mergedActionsBuilder.merge(event.actions());\n }\n\n return Event.builder()\n .id(Event.generateEventId())\n .invocationId(baseEvent.invocationId())\n .author(baseEvent.author())\n .branch(baseEvent.branch())\n .content(Optional.of(Content.builder().role(\"user\").parts(mergedParts).build()))\n .actions(mergedActionsBuilder.build())\n .timestamp(baseEvent.timestamp())\n .build();\n }\n\n private static Maybe> maybeInvokeBeforeToolCall(\n InvocationContext invocationContext,\n BaseTool tool,\n Map functionArgs,\n ToolContext toolContext) {\n if (invocationContext.agent() instanceof LlmAgent) {\n LlmAgent agent = (LlmAgent) invocationContext.agent();\n\n Optional> callbacksOpt = agent.beforeToolCallback();\n if (callbacksOpt.isEmpty() || callbacksOpt.get().isEmpty()) {\n return Maybe.empty();\n }\n List callbacks = callbacksOpt.get();\n\n return Flowable.fromIterable(callbacks)\n .concatMapMaybe(\n callback -> callback.call(invocationContext, tool, functionArgs, toolContext))\n .firstElement();\n }\n return Maybe.empty();\n }\n\n private static Maybe> maybeInvokeAfterToolCall(\n InvocationContext invocationContext,\n BaseTool tool,\n Map functionArgs,\n ToolContext toolContext,\n Map functionResult) {\n if (invocationContext.agent() instanceof LlmAgent) {\n LlmAgent agent = (LlmAgent) invocationContext.agent();\n Optional> callbacksOpt = agent.afterToolCallback();\n if (callbacksOpt.isEmpty() || callbacksOpt.get().isEmpty()) {\n return Maybe.empty();\n }\n List callbacks = callbacksOpt.get();\n\n return Flowable.fromIterable(callbacks)\n .concatMapMaybe(\n callback ->\n callback.call(invocationContext, tool, functionArgs, toolContext, functionResult))\n .firstElement();\n }\n return Maybe.empty();\n }\n\n private static Maybe> callTool(\n BaseTool tool, Map args, ToolContext toolContext) {\n Tracer tracer = Telemetry.getTracer();\n return Maybe.defer(\n () -> {\n Span span = tracer.spanBuilder(\"tool_call [\" + tool.name() + \"]\").startSpan();\n try (Scope scope = span.makeCurrent()) {\n Telemetry.traceToolCall(args);\n return tool.runAsync(args, toolContext)\n .toMaybe()\n .doOnError(span::recordException)\n .doFinally(span::end);\n } catch (RuntimeException e) {\n span.recordException(e);\n span.end();\n return Maybe.error(new RuntimeException(\"Failed to call tool: \" + tool.name(), e));\n }\n });\n }\n\n private static Event buildResponseEvent(\n BaseTool tool,\n Map response,\n ToolContext toolContext,\n InvocationContext invocationContext) {\n Tracer tracer = Telemetry.getTracer();\n Span span = tracer.spanBuilder(\"tool_response [\" + tool.name() + \"]\").startSpan();\n try (Scope scope = span.makeCurrent()) {\n // use a empty placeholder response if tool response is null.\n if (response == null) {\n response = new HashMap<>();\n }\n\n Part partFunctionResponse =\n Part.builder()\n .functionResponse(\n FunctionResponse.builder()\n .id(toolContext.functionCallId().orElse(\"\"))\n .name(tool.name())\n .response(response)\n .build())\n .build();\n\n Event event =\n Event.builder()\n .id(Event.generateEventId())\n .invocationId(invocationContext.invocationId())\n .author(invocationContext.agent().name())\n .branch(invocationContext.branch())\n .content(\n Optional.of(\n Content.builder()\n .role(\"user\")\n .parts(Collections.singletonList(partFunctionResponse))\n .build()))\n .actions(toolContext.eventActions())\n .build();\n Telemetry.traceToolResponse(invocationContext, event.id(), event);\n return event;\n } finally {\n span.end();\n }\n }\n\n private Functions() {}\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/agents/LlmAgent.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.agents;\n\nimport static java.util.stream.Collectors.joining;\n\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.google.adk.SchemaUtils;\nimport com.google.adk.agents.Callbacks.AfterAgentCallback;\nimport com.google.adk.agents.Callbacks.AfterAgentCallbackBase;\nimport com.google.adk.agents.Callbacks.AfterAgentCallbackSync;\nimport com.google.adk.agents.Callbacks.AfterModelCallback;\nimport com.google.adk.agents.Callbacks.AfterModelCallbackBase;\nimport com.google.adk.agents.Callbacks.AfterModelCallbackSync;\nimport com.google.adk.agents.Callbacks.AfterToolCallback;\nimport com.google.adk.agents.Callbacks.AfterToolCallbackBase;\nimport com.google.adk.agents.Callbacks.AfterToolCallbackSync;\nimport com.google.adk.agents.Callbacks.BeforeAgentCallback;\nimport com.google.adk.agents.Callbacks.BeforeAgentCallbackBase;\nimport com.google.adk.agents.Callbacks.BeforeAgentCallbackSync;\nimport com.google.adk.agents.Callbacks.BeforeModelCallback;\nimport com.google.adk.agents.Callbacks.BeforeModelCallbackBase;\nimport com.google.adk.agents.Callbacks.BeforeModelCallbackSync;\nimport com.google.adk.agents.Callbacks.BeforeToolCallback;\nimport com.google.adk.agents.Callbacks.BeforeToolCallbackBase;\nimport com.google.adk.agents.Callbacks.BeforeToolCallbackSync;\nimport com.google.adk.events.Event;\nimport com.google.adk.examples.BaseExampleProvider;\nimport com.google.adk.examples.Example;\nimport com.google.adk.flows.llmflows.AutoFlow;\nimport com.google.adk.flows.llmflows.BaseLlmFlow;\nimport com.google.adk.flows.llmflows.SingleFlow;\nimport com.google.adk.models.BaseLlm;\nimport com.google.adk.models.Model;\nimport com.google.adk.tools.BaseTool;\nimport com.google.adk.tools.BaseToolset;\nimport com.google.common.base.Preconditions;\nimport com.google.common.collect.ImmutableList;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.GenerateContentConfig;\nimport com.google.genai.types.Schema;\nimport io.reactivex.rxjava3.core.Flowable;\nimport io.reactivex.rxjava3.core.Maybe;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.concurrent.Executor;\nimport javax.annotation.Nullable;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/** The LLM-based agent. */\npublic class LlmAgent extends BaseAgent {\n\n private static final Logger logger = LoggerFactory.getLogger(LlmAgent.class);\n\n /**\n * Enum to define if contents of previous events should be included in requests to the underlying\n * LLM.\n */\n public enum IncludeContents {\n DEFAULT,\n NONE\n }\n\n private final Optional model;\n private final Instruction instruction;\n private final Instruction globalInstruction;\n private final List toolsUnion;\n private final Optional generateContentConfig;\n private final Optional exampleProvider;\n private final IncludeContents includeContents;\n\n private final boolean planning;\n private final Optional maxSteps;\n private final boolean disallowTransferToParent;\n private final boolean disallowTransferToPeers;\n private final Optional> beforeModelCallback;\n private final Optional> afterModelCallback;\n private final Optional> beforeToolCallback;\n private final Optional> afterToolCallback;\n private final Optional inputSchema;\n private final Optional outputSchema;\n private final Optional executor;\n private final Optional outputKey;\n\n private volatile Model resolvedModel;\n private final BaseLlmFlow llmFlow;\n\n protected LlmAgent(Builder builder) {\n super(\n builder.name,\n builder.description,\n builder.subAgents,\n builder.beforeAgentCallback,\n builder.afterAgentCallback);\n this.model = Optional.ofNullable(builder.model);\n this.instruction =\n builder.instruction == null ? new Instruction.Static(\"\") : builder.instruction;\n this.globalInstruction =\n builder.globalInstruction == null ? new Instruction.Static(\"\") : builder.globalInstruction;\n this.generateContentConfig = Optional.ofNullable(builder.generateContentConfig);\n this.exampleProvider = Optional.ofNullable(builder.exampleProvider);\n this.includeContents =\n builder.includeContents != null ? builder.includeContents : IncludeContents.DEFAULT;\n this.planning = builder.planning != null && builder.planning;\n this.maxSteps = Optional.ofNullable(builder.maxSteps);\n this.disallowTransferToParent = builder.disallowTransferToParent;\n this.disallowTransferToPeers = builder.disallowTransferToPeers;\n this.beforeModelCallback = Optional.ofNullable(builder.beforeModelCallback);\n this.afterModelCallback = Optional.ofNullable(builder.afterModelCallback);\n this.beforeToolCallback = Optional.ofNullable(builder.beforeToolCallback);\n this.afterToolCallback = Optional.ofNullable(builder.afterToolCallback);\n this.inputSchema = Optional.ofNullable(builder.inputSchema);\n this.outputSchema = Optional.ofNullable(builder.outputSchema);\n this.executor = Optional.ofNullable(builder.executor);\n this.outputKey = Optional.ofNullable(builder.outputKey);\n this.toolsUnion = builder.toolsUnion != null ? builder.toolsUnion : ImmutableList.of();\n\n this.llmFlow = determineLlmFlow();\n\n // Validate name not empty.\n Preconditions.checkArgument(!this.name().isEmpty(), \"Agent name cannot be empty.\");\n }\n\n /** Returns a {@link Builder} for {@link LlmAgent}. */\n public static Builder builder() {\n return new Builder();\n }\n\n /** Builder for {@link LlmAgent}. */\n public static class Builder {\n private String name;\n private String description;\n\n private Model model;\n\n private Instruction instruction;\n private Instruction globalInstruction;\n private ImmutableList subAgents;\n private ImmutableList toolsUnion;\n private GenerateContentConfig generateContentConfig;\n private BaseExampleProvider exampleProvider;\n private IncludeContents includeContents;\n private Boolean planning;\n private Integer maxSteps;\n private Boolean disallowTransferToParent;\n private Boolean disallowTransferToPeers;\n private ImmutableList beforeModelCallback;\n private ImmutableList afterModelCallback;\n private ImmutableList beforeAgentCallback;\n private ImmutableList afterAgentCallback;\n private ImmutableList beforeToolCallback;\n private ImmutableList afterToolCallback;\n private Schema inputSchema;\n private Schema outputSchema;\n private Executor executor;\n private String outputKey;\n\n @CanIgnoreReturnValue\n public Builder name(String name) {\n this.name = name;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder description(String description) {\n this.description = description;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder model(String model) {\n this.model = Model.builder().modelName(model).build();\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder model(BaseLlm model) {\n this.model = Model.builder().model(model).build();\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder instruction(Instruction instruction) {\n this.instruction = instruction;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder instruction(String instruction) {\n this.instruction = (instruction == null) ? null : new Instruction.Static(instruction);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder globalInstruction(Instruction globalInstruction) {\n this.globalInstruction = globalInstruction;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder globalInstruction(String globalInstruction) {\n this.globalInstruction =\n (globalInstruction == null) ? null : new Instruction.Static(globalInstruction);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder subAgents(List subAgents) {\n this.subAgents = ImmutableList.copyOf(subAgents);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder subAgents(BaseAgent... subAgents) {\n this.subAgents = ImmutableList.copyOf(subAgents);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder tools(List tools) {\n this.toolsUnion = ImmutableList.copyOf(tools);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder tools(Object... tools) {\n this.toolsUnion = ImmutableList.copyOf(tools);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder generateContentConfig(GenerateContentConfig generateContentConfig) {\n this.generateContentConfig = generateContentConfig;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder exampleProvider(BaseExampleProvider exampleProvider) {\n this.exampleProvider = exampleProvider;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder exampleProvider(List examples) {\n this.exampleProvider =\n new BaseExampleProvider() {\n @Override\n public List getExamples(String query) {\n return examples;\n }\n };\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder exampleProvider(Example... examples) {\n this.exampleProvider =\n new BaseExampleProvider() {\n @Override\n public ImmutableList getExamples(String query) {\n return ImmutableList.copyOf(examples);\n }\n };\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder includeContents(IncludeContents includeContents) {\n this.includeContents = includeContents;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder planning(boolean planning) {\n this.planning = planning;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder maxSteps(int maxSteps) {\n this.maxSteps = maxSteps;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder disallowTransferToParent(boolean disallowTransferToParent) {\n this.disallowTransferToParent = disallowTransferToParent;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder disallowTransferToPeers(boolean disallowTransferToPeers) {\n this.disallowTransferToPeers = disallowTransferToPeers;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeModelCallback(BeforeModelCallback beforeModelCallback) {\n this.beforeModelCallback = ImmutableList.of(beforeModelCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeModelCallback(List beforeModelCallback) {\n if (beforeModelCallback == null) {\n this.beforeModelCallback = null;\n } else if (beforeModelCallback.isEmpty()) {\n this.beforeModelCallback = ImmutableList.of();\n } else {\n ImmutableList.Builder builder = ImmutableList.builder();\n for (BeforeModelCallbackBase callback : beforeModelCallback) {\n if (callback instanceof BeforeModelCallback beforeModelCallbackInstance) {\n builder.add(beforeModelCallbackInstance);\n } else if (callback instanceof BeforeModelCallbackSync beforeModelCallbackSyncInstance) {\n builder.add(\n (BeforeModelCallback)\n (callbackContext, llmRequest) ->\n Maybe.fromOptional(\n beforeModelCallbackSyncInstance.call(callbackContext, llmRequest)));\n } else {\n logger.warn(\n \"Invalid beforeModelCallback callback type: %s. Ignoring this callback.\",\n callback.getClass().getName());\n }\n }\n this.beforeModelCallback = builder.build();\n }\n\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeModelCallbackSync(BeforeModelCallbackSync beforeModelCallbackSync) {\n this.beforeModelCallback =\n ImmutableList.of(\n (callbackContext, llmRequest) ->\n Maybe.fromOptional(beforeModelCallbackSync.call(callbackContext, llmRequest)));\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterModelCallback(AfterModelCallback afterModelCallback) {\n this.afterModelCallback = ImmutableList.of(afterModelCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterModelCallback(List afterModelCallback) {\n if (afterModelCallback == null) {\n this.afterModelCallback = null;\n } else if (afterModelCallback.isEmpty()) {\n this.afterModelCallback = ImmutableList.of();\n } else {\n ImmutableList.Builder builder = ImmutableList.builder();\n for (AfterModelCallbackBase callback : afterModelCallback) {\n if (callback instanceof AfterModelCallback afterModelCallbackInstance) {\n builder.add(afterModelCallbackInstance);\n } else if (callback instanceof AfterModelCallbackSync afterModelCallbackSyncInstance) {\n builder.add(\n (AfterModelCallback)\n (callbackContext, llmResponse) ->\n Maybe.fromOptional(\n afterModelCallbackSyncInstance.call(callbackContext, llmResponse)));\n } else {\n logger.warn(\n \"Invalid afterModelCallback callback type: %s. Ignoring this callback.\",\n callback.getClass().getName());\n }\n }\n this.afterModelCallback = builder.build();\n }\n\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterModelCallbackSync(AfterModelCallbackSync afterModelCallbackSync) {\n this.afterModelCallback =\n ImmutableList.of(\n (callbackContext, llmResponse) ->\n Maybe.fromOptional(afterModelCallbackSync.call(callbackContext, llmResponse)));\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeAgentCallback(BeforeAgentCallback beforeAgentCallback) {\n this.beforeAgentCallback = ImmutableList.of(beforeAgentCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeAgentCallback(List beforeAgentCallback) {\n this.beforeAgentCallback = CallbackUtil.getBeforeAgentCallbacks(beforeAgentCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeAgentCallbackSync(BeforeAgentCallbackSync beforeAgentCallbackSync) {\n this.beforeAgentCallback =\n ImmutableList.of(\n (callbackContext) ->\n Maybe.fromOptional(beforeAgentCallbackSync.call(callbackContext)));\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterAgentCallback(AfterAgentCallback afterAgentCallback) {\n this.afterAgentCallback = ImmutableList.of(afterAgentCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterAgentCallback(List afterAgentCallback) {\n this.afterAgentCallback = CallbackUtil.getAfterAgentCallbacks(afterAgentCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterAgentCallbackSync(AfterAgentCallbackSync afterAgentCallbackSync) {\n this.afterAgentCallback =\n ImmutableList.of(\n (callbackContext) ->\n Maybe.fromOptional(afterAgentCallbackSync.call(callbackContext)));\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeToolCallback(BeforeToolCallback beforeToolCallback) {\n this.beforeToolCallback = ImmutableList.of(beforeToolCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeToolCallback(@Nullable List beforeToolCallbacks) {\n if (beforeToolCallbacks == null) {\n this.beforeToolCallback = null;\n } else if (beforeToolCallbacks.isEmpty()) {\n this.beforeToolCallback = ImmutableList.of();\n } else {\n ImmutableList.Builder builder = ImmutableList.builder();\n for (BeforeToolCallbackBase callback : beforeToolCallbacks) {\n if (callback instanceof BeforeToolCallback beforeToolCallbackInstance) {\n builder.add(beforeToolCallbackInstance);\n } else if (callback instanceof BeforeToolCallbackSync beforeToolCallbackSyncInstance) {\n builder.add(\n (invocationContext, baseTool, input, toolContext) ->\n Maybe.fromOptional(\n beforeToolCallbackSyncInstance.call(\n invocationContext, baseTool, input, toolContext)));\n } else {\n logger.warn(\n \"Invalid beforeToolCallback callback type: {}. Ignoring this callback.\",\n callback.getClass().getName());\n }\n }\n this.beforeToolCallback = builder.build();\n }\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeToolCallbackSync(BeforeToolCallbackSync beforeToolCallbackSync) {\n this.beforeToolCallback =\n ImmutableList.of(\n (invocationContext, baseTool, input, toolContext) ->\n Maybe.fromOptional(\n beforeToolCallbackSync.call(\n invocationContext, baseTool, input, toolContext)));\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterToolCallback(AfterToolCallback afterToolCallback) {\n this.afterToolCallback = ImmutableList.of(afterToolCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterToolCallback(@Nullable List afterToolCallbacks) {\n if (afterToolCallbacks == null) {\n this.afterToolCallback = null;\n } else if (afterToolCallbacks.isEmpty()) {\n this.afterToolCallback = ImmutableList.of();\n } else {\n ImmutableList.Builder builder = ImmutableList.builder();\n for (AfterToolCallbackBase callback : afterToolCallbacks) {\n if (callback instanceof AfterToolCallback afterToolCallbackInstance) {\n builder.add(afterToolCallbackInstance);\n } else if (callback instanceof AfterToolCallbackSync afterToolCallbackSyncInstance) {\n builder.add(\n (invocationContext, baseTool, input, toolContext, response) ->\n Maybe.fromOptional(\n afterToolCallbackSyncInstance.call(\n invocationContext, baseTool, input, toolContext, response)));\n } else {\n logger.warn(\n \"Invalid afterToolCallback callback type: {}. Ignoring this callback.\",\n callback.getClass().getName());\n }\n }\n this.afterToolCallback = builder.build();\n }\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterToolCallbackSync(AfterToolCallbackSync afterToolCallbackSync) {\n this.afterToolCallback =\n ImmutableList.of(\n (invocationContext, baseTool, input, toolContext, response) ->\n Maybe.fromOptional(\n afterToolCallbackSync.call(\n invocationContext, baseTool, input, toolContext, response)));\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder inputSchema(Schema inputSchema) {\n this.inputSchema = inputSchema;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder outputSchema(Schema outputSchema) {\n this.outputSchema = outputSchema;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder executor(Executor executor) {\n this.executor = executor;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder outputKey(String outputKey) {\n this.outputKey = outputKey;\n return this;\n }\n\n protected void validate() {\n this.disallowTransferToParent =\n this.disallowTransferToParent != null && this.disallowTransferToParent;\n this.disallowTransferToPeers =\n this.disallowTransferToPeers != null && this.disallowTransferToPeers;\n\n if (this.outputSchema != null) {\n if (!this.disallowTransferToParent || !this.disallowTransferToPeers) {\n System.err.println(\n \"Warning: Invalid config for agent \"\n + this.name\n + \": outputSchema cannot co-exist with agent transfer\"\n + \" configurations. Setting disallowTransferToParent=true and\"\n + \" disallowTransferToPeers=true.\");\n this.disallowTransferToParent = true;\n this.disallowTransferToPeers = true;\n }\n\n if (this.subAgents != null && !this.subAgents.isEmpty()) {\n throw new IllegalArgumentException(\n \"Invalid config for agent \"\n + this.name\n + \": if outputSchema is set, subAgents must be empty to disable agent\"\n + \" transfer.\");\n }\n if (this.toolsUnion != null && !this.toolsUnion.isEmpty()) {\n throw new IllegalArgumentException(\n \"Invalid config for agent \"\n + this.name\n + \": if outputSchema is set, tools must be empty.\");\n }\n }\n }\n\n public LlmAgent build() {\n validate();\n return new LlmAgent(this);\n }\n }\n\n protected BaseLlmFlow determineLlmFlow() {\n if (disallowTransferToParent() && disallowTransferToPeers() && subAgents().isEmpty()) {\n return new SingleFlow(maxSteps);\n } else {\n return new AutoFlow(maxSteps);\n }\n }\n\n private void maybeSaveOutputToState(Event event) {\n if (outputKey().isPresent() && event.finalResponse() && event.content().isPresent()) {\n // Concatenate text from all parts.\n Object output;\n String rawResult =\n event.content().flatMap(Content::parts).orElse(ImmutableList.of()).stream()\n .map(part -> part.text().orElse(\"\"))\n .collect(joining());\n\n Optional outputSchema = outputSchema();\n if (outputSchema.isPresent()) {\n try {\n Map validatedMap =\n SchemaUtils.validateOutputSchema(rawResult, outputSchema.get());\n output = validatedMap;\n } catch (JsonProcessingException e) {\n System.err.println(\n \"Error: LlmAgent output for outputKey '\"\n + outputKey().get()\n + \"' was not valid JSON, despite an outputSchema being present.\"\n + \" Saving raw output to state. Error: \"\n + e.getMessage());\n output = rawResult;\n } catch (IllegalArgumentException e) {\n System.err.println(\n \"Error: LlmAgent output for outputKey '\"\n + outputKey().get()\n + \"' did not match the outputSchema.\"\n + \" Saving raw output to state. Error: \"\n + e.getMessage());\n output = rawResult;\n }\n } else {\n output = rawResult;\n }\n event.actions().stateDelta().put(outputKey().get(), output);\n }\n }\n\n @Override\n protected Flowable runAsyncImpl(InvocationContext invocationContext) {\n return llmFlow.run(invocationContext).doOnNext(this::maybeSaveOutputToState);\n }\n\n @Override\n protected Flowable runLiveImpl(InvocationContext invocationContext) {\n return llmFlow.runLive(invocationContext).doOnNext(this::maybeSaveOutputToState);\n }\n\n /**\n * Constructs the text instruction for this agent based on the {@link #instruction} field.\n *\n *

This method is only for use by Agent Development Kit.\n *\n * @param context The context to retrieve the session state.\n * @return The resolved instruction as a {@link Single} wrapped string.\n */\n public Single canonicalInstruction(ReadonlyContext context) {\n if (instruction instanceof Instruction.Static staticInstr) {\n return Single.just(staticInstr.instruction());\n } else if (instruction instanceof Instruction.Provider provider) {\n return provider.getInstruction().apply(context);\n }\n throw new IllegalStateException(\"Unknown Instruction subtype: \" + instruction.getClass());\n }\n\n /**\n * Constructs the text global instruction for this agent based on the {@link #globalInstruction}\n * field.\n *\n *

This method is only for use by Agent Development Kit.\n *\n * @param context The context to retrieve the session state.\n * @return The resolved global instruction as a {@link Single} wrapped string.\n */\n public Single canonicalGlobalInstruction(ReadonlyContext context) {\n if (globalInstruction instanceof Instruction.Static staticInstr) {\n return Single.just(staticInstr.instruction());\n } else if (globalInstruction instanceof Instruction.Provider provider) {\n return provider.getInstruction().apply(context);\n }\n throw new IllegalStateException(\"Unknown Instruction subtype: \" + instruction.getClass());\n }\n\n /**\n * Constructs the list of tools for this agent based on the {@link #tools} field.\n *\n *

This method is only for use by Agent Development Kit.\n *\n * @param context The context to retrieve the session state.\n * @return The resolved list of tools as a {@link Single} wrapped list of {@link BaseTool}.\n */\n public Flowable canonicalTools(Optional context) {\n List> toolFlowables = new ArrayList<>();\n for (Object toolOrToolset : toolsUnion) {\n if (toolOrToolset instanceof BaseTool baseTool) {\n toolFlowables.add(Flowable.just(baseTool));\n } else if (toolOrToolset instanceof BaseToolset baseToolset) {\n toolFlowables.add(baseToolset.getTools(context.orElse(null)));\n } else {\n throw new IllegalArgumentException(\n \"Object in tools list is not of a supported type: \"\n + toolOrToolset.getClass().getName());\n }\n }\n return Flowable.concat(toolFlowables);\n }\n\n /** Overload of canonicalTools that defaults to an empty context. */\n public Flowable canonicalTools() {\n return canonicalTools(Optional.empty());\n }\n\n /** Convenience overload of canonicalTools that accepts a non-optional ReadonlyContext. */\n public Flowable canonicalTools(ReadonlyContext context) {\n return canonicalTools(Optional.ofNullable(context));\n }\n\n public Instruction instruction() {\n return instruction;\n }\n\n public Instruction globalInstruction() {\n return globalInstruction;\n }\n\n public Optional model() {\n return model;\n }\n\n public boolean planning() {\n return planning;\n }\n\n public Optional maxSteps() {\n return maxSteps;\n }\n\n public Optional generateContentConfig() {\n return generateContentConfig;\n }\n\n public Optional exampleProvider() {\n return exampleProvider;\n }\n\n public IncludeContents includeContents() {\n return includeContents;\n }\n\n public List tools() {\n return canonicalTools().toList().blockingGet();\n }\n\n public List toolsUnion() {\n return toolsUnion;\n }\n\n public boolean disallowTransferToParent() {\n return disallowTransferToParent;\n }\n\n public boolean disallowTransferToPeers() {\n return disallowTransferToPeers;\n }\n\n public Optional> beforeModelCallback() {\n return beforeModelCallback;\n }\n\n public Optional> afterModelCallback() {\n return afterModelCallback;\n }\n\n public Optional> beforeToolCallback() {\n return beforeToolCallback;\n }\n\n public Optional> afterToolCallback() {\n return afterToolCallback;\n }\n\n public Optional inputSchema() {\n return inputSchema;\n }\n\n public Optional outputSchema() {\n return outputSchema;\n }\n\n public Optional executor() {\n return executor;\n }\n\n public Optional outputKey() {\n return outputKey;\n }\n\n public Model resolvedModel() {\n if (resolvedModel == null) {\n synchronized (this) {\n if (resolvedModel == null) {\n resolvedModel = resolveModelInternal();\n }\n }\n }\n return resolvedModel;\n }\n\n /**\n * Resolves the model for this agent, checking first if it is defined locally, then searching\n * through ancestors.\n *\n *

This method is only for use by Agent Development Kit.\n *\n * @return The resolved {@link Model} for this agent.\n * @throws IllegalStateException if no model is found for this agent or its ancestors.\n */\n private Model resolveModelInternal() {\n if (this.model.isPresent()) {\n if (this.model().isPresent()) {\n return this.model.get();\n }\n }\n BaseAgent current = this.parentAgent();\n while (current != null) {\n if (current instanceof LlmAgent) {\n return ((LlmAgent) current).resolvedModel();\n }\n current = current.parentAgent();\n }\n throw new IllegalStateException(\"No model found for agent \" + name() + \" or its ancestors.\");\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/models/LlmRequest.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.models;\n\nimport static com.google.common.collect.ImmutableList.toImmutableList;\nimport static com.google.common.collect.ImmutableMap.toImmutableMap;\n\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonIgnore;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.databind.annotation.JsonDeserialize;\nimport com.google.adk.JsonBaseModel;\nimport com.google.adk.tools.BaseTool;\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.GenerateContentConfig;\nimport com.google.genai.types.LiveConnectConfig;\nimport com.google.genai.types.Part;\nimport com.google.genai.types.Schema;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.stream.Stream;\n\n/** Represents a request to be sent to the LLM. */\n@AutoValue\n@JsonDeserialize(builder = LlmRequest.Builder.class)\npublic abstract class LlmRequest extends JsonBaseModel {\n\n /**\n * Returns the name of the LLM model to be used. If not set, the default model of the LLM class\n * will be used.\n *\n * @return An optional string representing the model name.\n */\n @JsonProperty(\"model\")\n public abstract Optional model();\n\n /**\n * Returns the list of content sent to the LLM.\n *\n * @return A list of {@link Content} objects.\n */\n @JsonProperty(\"contents\")\n public abstract List contents();\n\n /**\n * Returns the configuration for content generation.\n *\n * @return An optional {@link GenerateContentConfig} object containing the generation settings.\n */\n @JsonProperty(\"config\")\n public abstract Optional config();\n\n /**\n * Returns the configuration for live connections. Populated using the RunConfig in the\n * InvocationContext.\n *\n * @return An optional {@link LiveConnectConfig} object containing the live connection settings.\n */\n @JsonProperty(\"liveConnectConfig\")\n public abstract LiveConnectConfig liveConnectConfig();\n\n /**\n * Returns a map of tools available to the LLM.\n *\n * @return A map where keys are tool names and values are {@link BaseTool} instances.\n */\n @JsonIgnore\n public abstract Map tools();\n\n /** returns the first system instruction text from the request if present. */\n @JsonIgnore\n public Optional getFirstSystemInstruction() {\n return this.config()\n .flatMap(GenerateContentConfig::systemInstruction)\n .flatMap(content -> content.parts().flatMap(partList -> partList.stream().findFirst()))\n .flatMap(Part::text);\n }\n\n /** Returns all system instruction texts from the request as an immutable list. */\n @JsonIgnore\n public ImmutableList getSystemInstructions() {\n return config()\n .flatMap(GenerateContentConfig::systemInstruction)\n .flatMap(Content::parts)\n .map(\n partList ->\n partList.stream()\n .map(Part::text)\n .flatMap(Optional::stream)\n .collect(toImmutableList()))\n .orElse(ImmutableList.of());\n }\n\n public static Builder builder() {\n return new AutoValue_LlmRequest.Builder()\n .tools(ImmutableMap.of())\n .contents(ImmutableList.of())\n .liveConnectConfig(LiveConnectConfig.builder().build());\n }\n\n public abstract Builder toBuilder();\n\n /** Builder for constructing {@link LlmRequest} instances. */\n @AutoValue.Builder\n public abstract static class Builder {\n\n @JsonCreator\n private static Builder create() {\n return builder();\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"model\")\n public abstract Builder model(String model);\n\n @CanIgnoreReturnValue\n @JsonProperty(\"contents\")\n public abstract Builder contents(List contents);\n\n @CanIgnoreReturnValue\n @JsonProperty(\"config\")\n public abstract Builder config(GenerateContentConfig config);\n\n public abstract Optional config();\n\n @CanIgnoreReturnValue\n @JsonProperty(\"liveConnectConfig\")\n public abstract Builder liveConnectConfig(LiveConnectConfig liveConnectConfig);\n\n abstract LiveConnectConfig liveConnectConfig();\n\n @CanIgnoreReturnValue\n abstract Builder tools(Map tools);\n\n abstract Map tools();\n\n @CanIgnoreReturnValue\n public final Builder appendInstructions(List instructions) {\n if (instructions.isEmpty()) {\n return this;\n }\n GenerateContentConfig config = config().orElse(GenerateContentConfig.builder().build());\n ImmutableList.Builder parts = ImmutableList.builder();\n if (config.systemInstruction().isPresent()) {\n parts.addAll(config.systemInstruction().get().parts().orElse(ImmutableList.of()));\n }\n parts.addAll(\n instructions.stream()\n .map(instruction -> Part.builder().text(instruction).build())\n .collect(toImmutableList()));\n config(\n config.toBuilder()\n .systemInstruction(\n Content.builder()\n .parts(parts.build())\n .role(\n config\n .systemInstruction()\n .map(c -> c.role().orElse(\"user\"))\n .orElse(\"user\"))\n .build())\n .build());\n\n LiveConnectConfig liveConfig = liveConnectConfig();\n ImmutableList.Builder livePartsBuilder = ImmutableList.builder();\n\n if (liveConfig.systemInstruction().isPresent()) {\n livePartsBuilder.addAll(\n liveConfig.systemInstruction().get().parts().orElse(ImmutableList.of()));\n }\n\n livePartsBuilder.addAll(\n instructions.stream()\n .map(instruction -> Part.builder().text(instruction).build())\n .collect(toImmutableList()));\n\n return liveConnectConfig(\n liveConfig.toBuilder()\n .systemInstruction(\n Content.builder()\n .parts(livePartsBuilder.build())\n .role(\n liveConfig\n .systemInstruction()\n .map(c -> c.role().orElse(\"user\"))\n .orElse(\"user\"))\n .build())\n .build());\n }\n\n @CanIgnoreReturnValue\n public final Builder appendTools(List tools) {\n if (tools.isEmpty()) {\n return this;\n }\n return tools(\n ImmutableMap.builder()\n .putAll(\n Stream.concat(tools.stream(), tools().values().stream())\n .collect(\n toImmutableMap(\n BaseTool::name,\n tool -> tool,\n (tool1, tool2) -> {\n throw new IllegalArgumentException(\n String.format(\"Duplicate tool name: %s\", tool1.name()));\n })))\n .buildOrThrow());\n }\n\n /**\n * Sets the output schema for the LLM response. If set, The output content will always be a JSON\n * string that conforms to the schema.\n */\n @CanIgnoreReturnValue\n public final Builder outputSchema(Schema schema) {\n GenerateContentConfig config = config().orElse(GenerateContentConfig.builder().build());\n return config(\n config.toBuilder().responseSchema(schema).responseMimeType(\"application/json\").build());\n }\n\n public abstract LlmRequest build();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/applicationintegrationtoolset/ConnectionsClient.java", "package com.google.adk.tools.applicationintegrationtoolset;\n\nimport static com.google.common.base.Strings.isNullOrEmpty;\n\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.google.adk.tools.applicationintegrationtoolset.IntegrationConnectorTool.HttpExecutor;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport java.io.IOException;\nimport java.net.URI;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\n\n/**\n * Utility class for interacting with the Google Cloud Connectors API.\n *\n *

This class provides methods to fetch connection details, schemas for entities and actions, and\n * to generate OpenAPI specifications for creating tools based on these connections.\n */\npublic class ConnectionsClient {\n\n private final String project;\n private final String location;\n private final String connection;\n private static final String CONNECTOR_URL = \"https://connectors.googleapis.com\";\n private final HttpExecutor httpExecutor;\n private final ObjectMapper objectMapper;\n\n /** Represents details of a connection. */\n public static class ConnectionDetails {\n public String name;\n public String serviceName;\n public String host;\n }\n\n /** Represents the schema and available operations for an entity. */\n public static class EntitySchemaAndOperations {\n public Map schema;\n public List operations;\n }\n\n /** Represents the schema for an action. */\n public static class ActionSchema {\n public Map inputSchema;\n public Map outputSchema;\n public String description;\n public String displayName;\n }\n\n /**\n * Initializes the ConnectionsClient.\n *\n * @param project The Google Cloud project ID.\n * @param location The Google Cloud location (e.g., us-central1).\n * @param connection The connection name.\n */\n public ConnectionsClient(\n String project,\n String location,\n String connection,\n HttpExecutor httpExecutor,\n ObjectMapper objectMapper) {\n this.project = project;\n this.location = location;\n this.connection = connection;\n this.httpExecutor = httpExecutor;\n this.objectMapper = objectMapper;\n }\n\n /**\n * Retrieves service details for a given connection.\n *\n * @return A {@link ConnectionDetails} object with the connection's info.\n * @throws IOException If there is an issue with network communication or credentials.\n * @throws InterruptedException If the thread is interrupted during the API call.\n */\n public ConnectionDetails getConnectionDetails() throws IOException, InterruptedException {\n String url =\n String.format(\n \"%s/v1/projects/%s/locations/%s/connections/%s?view=BASIC\",\n CONNECTOR_URL, project, location, connection);\n\n HttpResponse response = executeApiCall(url);\n Map connectionData = parseJson(response.body());\n\n ConnectionDetails details = new ConnectionDetails();\n details.name = (String) connectionData.getOrDefault(\"name\", \"\");\n details.serviceName = (String) connectionData.getOrDefault(\"serviceDirectory\", \"\");\n details.host = (String) connectionData.getOrDefault(\"host\", \"\");\n if (details.host != null && !details.host.isEmpty()) {\n details.serviceName = (String) connectionData.getOrDefault(\"tlsServiceDirectory\", \"\");\n }\n return details;\n }\n\n /**\n * Retrieves the JSON schema and available operations for a given entity.\n *\n * @param entity The entity name.\n * @return A {@link EntitySchemaAndOperations} object.\n * @throws IOException If there is an issue with network communication or credentials.\n * @throws InterruptedException If the thread is interrupted during polling.\n */\n @SuppressWarnings(\"unchecked\")\n public EntitySchemaAndOperations getEntitySchemaAndOperations(String entity)\n throws IOException, InterruptedException {\n String url =\n String.format(\n \"%s/v1/projects/%s/locations/%s/connections/%s/connectionSchemaMetadata:getEntityType?entityId=%s\",\n CONNECTOR_URL, project, location, connection, entity);\n\n HttpResponse initialResponse = executeApiCall(url);\n String operationId = (String) parseJson(initialResponse.body()).get(\"name\");\n\n if (isNullOrEmpty(operationId)) {\n throw new IOException(\"Failed to get operation ID for entity: \" + entity);\n }\n\n Map operationResponse = pollOperation(operationId);\n Map responseData =\n (Map) operationResponse.getOrDefault(\"response\", ImmutableMap.of());\n\n Map schema =\n (Map) responseData.getOrDefault(\"jsonSchema\", ImmutableMap.of());\n List operations =\n (List) responseData.getOrDefault(\"operations\", ImmutableList.of());\n EntitySchemaAndOperations entitySchemaAndOperations = new EntitySchemaAndOperations();\n entitySchemaAndOperations.schema = schema;\n entitySchemaAndOperations.operations = operations;\n return entitySchemaAndOperations;\n }\n\n /**\n * Retrieves the input and output JSON schema for a given action.\n *\n * @param action The action name.\n * @return An {@link ActionSchema} object.\n * @throws IOException If there is an issue with network communication or credentials.\n * @throws InterruptedException If the thread is interrupted during polling.\n */\n @SuppressWarnings(\"unchecked\")\n public ActionSchema getActionSchema(String action) throws IOException, InterruptedException {\n String url =\n String.format(\n \"%s/v1/projects/%s/locations/%s/connections/%s/connectionSchemaMetadata:getAction?actionId=%s\",\n CONNECTOR_URL, project, location, connection, action);\n\n HttpResponse initialResponse = executeApiCall(url);\n String operationId = (String) parseJson(initialResponse.body()).get(\"name\");\n\n if (isNullOrEmpty(operationId)) {\n throw new IOException(\"Failed to get operation ID for action: \" + action);\n }\n\n Map operationResponse = pollOperation(operationId);\n Map responseData =\n (Map) operationResponse.getOrDefault(\"response\", ImmutableMap.of());\n\n ActionSchema actionSchema = new ActionSchema();\n actionSchema.inputSchema =\n (Map) responseData.getOrDefault(\"inputJsonSchema\", ImmutableMap.of());\n actionSchema.outputSchema =\n (Map) responseData.getOrDefault(\"outputJsonSchema\", ImmutableMap.of());\n actionSchema.description = (String) responseData.getOrDefault(\"description\", \"\");\n actionSchema.displayName = (String) responseData.getOrDefault(\"displayName\", \"\");\n\n return actionSchema;\n }\n\n private HttpResponse executeApiCall(String url) throws IOException, InterruptedException {\n HttpRequest request =\n HttpRequest.newBuilder()\n .uri(URI.create(url))\n .header(\"Content-Type\", \"application/json\")\n .header(\"Authorization\", \"Bearer \" + httpExecutor.getToken())\n .GET()\n .build();\n\n HttpResponse response =\n httpExecutor.send(request, HttpResponse.BodyHandlers.ofString());\n\n if (response.statusCode() >= 400) {\n String body = response.body();\n if (response.statusCode() == 400 || response.statusCode() == 404) {\n throw new IllegalArgumentException(\n String.format(\n \"Invalid request. Please check the provided values of project(%s), location(%s),\"\n + \" connection(%s). Error: %s\",\n project, location, connection, body));\n }\n if (response.statusCode() == 401 || response.statusCode() == 403) {\n throw new SecurityException(\n String.format(\"Permission error (status %d): %s\", response.statusCode(), body));\n }\n throw new IOException(\n String.format(\"API call failed with status %d: %s\", response.statusCode(), body));\n }\n return response;\n }\n\n private Map pollOperation(String operationId)\n throws IOException, InterruptedException {\n boolean operationDone = false;\n Map operationResponse = null;\n\n while (!operationDone) {\n String getOperationUrl = String.format(\"%s/v1/%s\", CONNECTOR_URL, operationId);\n HttpResponse response = executeApiCall(getOperationUrl);\n operationResponse = parseJson(response.body());\n\n Object doneObj = operationResponse.get(\"done\");\n if (doneObj instanceof Boolean b) {\n operationDone = b;\n }\n\n if (!operationDone) {\n Thread.sleep(1000);\n }\n }\n return operationResponse;\n }\n\n /**\n * Converts a JSON Schema dictionary to an OpenAPI schema dictionary.\n *\n * @param jsonSchema The input JSON schema map.\n * @return The converted OpenAPI schema map.\n */\n public Map convertJsonSchemaToOpenApiSchema(Map jsonSchema) {\n Map openapiSchema = new HashMap<>();\n\n if (jsonSchema.containsKey(\"description\")) {\n openapiSchema.put(\"description\", jsonSchema.get(\"description\"));\n }\n\n if (jsonSchema.containsKey(\"type\")) {\n Object type = jsonSchema.get(\"type\");\n if (type instanceof List) {\n List typeList = (List) type;\n if (typeList.contains(\"null\")) {\n openapiSchema.put(\"nullable\", true);\n typeList.stream()\n .filter(t -> t instanceof String && !t.equals(\"null\"))\n .findFirst()\n .ifPresent(t -> openapiSchema.put(\"type\", t));\n } else if (!typeList.isEmpty()) {\n openapiSchema.put(\"type\", typeList.get(0));\n }\n } else {\n openapiSchema.put(\"type\", type);\n }\n }\n if (Objects.equals(openapiSchema.get(\"type\"), \"object\")\n && jsonSchema.containsKey(\"properties\")) {\n @SuppressWarnings(\"unchecked\")\n Map> properties =\n (Map>) jsonSchema.get(\"properties\");\n Map convertedProperties = new HashMap<>();\n for (Map.Entry> entry : properties.entrySet()) {\n convertedProperties.put(entry.getKey(), convertJsonSchemaToOpenApiSchema(entry.getValue()));\n }\n openapiSchema.put(\"properties\", convertedProperties);\n } else if (Objects.equals(openapiSchema.get(\"type\"), \"array\")\n && jsonSchema.containsKey(\"items\")) {\n @SuppressWarnings(\"unchecked\")\n Map itemsSchema = (Map) jsonSchema.get(\"items\");\n openapiSchema.put(\"items\", convertJsonSchemaToOpenApiSchema(itemsSchema));\n }\n\n return openapiSchema;\n }\n\n public Map connectorPayload(Map jsonSchema) {\n return convertJsonSchemaToOpenApiSchema(jsonSchema);\n }\n\n private Map parseJson(String json) throws IOException {\n return objectMapper.readValue(json, new TypeReference<>() {});\n }\n\n public static ImmutableMap getConnectorBaseSpec() {\n return ImmutableMap.ofEntries(\n Map.entry(\"openapi\", \"3.0.1\"),\n Map.entry(\n \"info\",\n ImmutableMap.of(\n \"title\", \"ExecuteConnection\",\n \"description\", \"This tool can execute a query on connection\",\n \"version\", \"4\")),\n Map.entry(\n \"servers\",\n ImmutableList.of(ImmutableMap.of(\"url\", \"https://integrations.googleapis.com\"))),\n Map.entry(\n \"security\",\n ImmutableList.of(\n ImmutableMap.of(\n \"google_auth\",\n ImmutableList.of(\"https://www.googleapis.com/auth/cloud-platform\")))),\n Map.entry(\"paths\", ImmutableMap.of()),\n Map.entry(\n \"components\",\n ImmutableMap.ofEntries(\n Map.entry(\n \"schemas\",\n ImmutableMap.ofEntries(\n Map.entry(\n \"operation\",\n ImmutableMap.of(\n \"type\", \"string\",\n \"default\", \"LIST_ENTITIES\",\n \"description\",\n \"Operation to execute. Possible values are LIST_ENTITIES,\"\n + \" GET_ENTITY, CREATE_ENTITY, UPDATE_ENTITY, DELETE_ENTITY\"\n + \" in case of entities. EXECUTE_ACTION in case of\"\n + \" actions. and EXECUTE_QUERY in case of custom\"\n + \" queries.\")),\n Map.entry(\n \"entityId\",\n ImmutableMap.of(\"type\", \"string\", \"description\", \"Name of the entity\")),\n Map.entry(\"connectorInputPayload\", ImmutableMap.of(\"type\", \"object\")),\n Map.entry(\n \"filterClause\",\n ImmutableMap.of(\n \"type\", \"string\",\n \"default\", \"\",\n \"description\", \"WHERE clause in SQL query\")),\n Map.entry(\n \"pageSize\",\n ImmutableMap.of(\n \"type\", \"integer\",\n \"default\", 50,\n \"description\", \"Number of entities to return in the response\")),\n Map.entry(\n \"pageToken\",\n ImmutableMap.of(\n \"type\", \"string\",\n \"default\", \"\",\n \"description\", \"Page token to return the next page of entities\")),\n Map.entry(\n \"connectionName\",\n ImmutableMap.of(\n \"type\", \"string\",\n \"default\", \"\",\n \"description\", \"Connection resource name to run the query for\")),\n Map.entry(\n \"serviceName\",\n ImmutableMap.of(\n \"type\", \"string\",\n \"default\", \"\",\n \"description\", \"Service directory for the connection\")),\n Map.entry(\n \"host\",\n ImmutableMap.of(\n \"type\", \"string\",\n \"default\", \"\",\n \"description\", \"Host name incase of tls service directory\")),\n Map.entry(\n \"entity\",\n ImmutableMap.of(\n \"type\", \"string\",\n \"default\", \"Issues\",\n \"description\", \"Entity to run the query for\")),\n Map.entry(\n \"action\",\n ImmutableMap.of(\n \"type\", \"string\",\n \"default\", \"ExecuteCustomQuery\",\n \"description\", \"Action to run the query for\")),\n Map.entry(\n \"query\",\n ImmutableMap.of(\n \"type\", \"string\",\n \"default\", \"\",\n \"description\", \"Custom Query to execute on the connection\")),\n Map.entry(\n \"timeout\",\n ImmutableMap.of(\n \"type\", \"integer\",\n \"default\", 120,\n \"description\", \"Timeout in seconds for execution of custom query\")),\n Map.entry(\n \"sortByColumns\",\n ImmutableMap.of(\n \"type\",\n \"array\",\n \"items\",\n ImmutableMap.of(\"type\", \"string\"),\n \"default\",\n ImmutableList.of(),\n \"description\",\n \"Column to sort the results by\")),\n Map.entry(\"connectorOutputPayload\", ImmutableMap.of(\"type\", \"object\")),\n Map.entry(\"nextPageToken\", ImmutableMap.of(\"type\", \"string\")),\n Map.entry(\n \"execute-connector_Response\",\n ImmutableMap.of(\n \"required\", ImmutableList.of(\"connectorOutputPayload\"),\n \"type\", \"object\",\n \"properties\",\n ImmutableMap.of(\n \"connectorOutputPayload\",\n ImmutableMap.of(\n \"$ref\", \"#/components/schemas/connectorOutputPayload\"),\n \"nextPageToken\",\n ImmutableMap.of(\n \"$ref\", \"#/components/schemas/nextPageToken\")))))),\n Map.entry(\n \"securitySchemes\",\n ImmutableMap.of(\n \"google_auth\",\n ImmutableMap.of(\n \"type\",\n \"oauth2\",\n \"flows\",\n ImmutableMap.of(\n \"implicit\",\n ImmutableMap.of(\n \"authorizationUrl\",\n \"https://accounts.google.com/o/oauth2/auth\",\n \"scopes\",\n ImmutableMap.of(\n \"https://www.googleapis.com/auth/cloud-platform\",\n \"Auth for google cloud services\")))))))));\n }\n\n public static ImmutableMap getActionOperation(\n String action,\n String operation,\n String actionDisplayName,\n String toolName,\n String toolInstructions) {\n String description = \"Use this tool to execute \" + action;\n if (Objects.equals(operation, \"EXECUTE_QUERY\")) {\n description +=\n \" Use pageSize = 50 and timeout = 120 until user specifies a different value\"\n + \" otherwise. If user provides a query in natural language, convert it to SQL query\"\n + \" and then execute it using the tool.\";\n }\n\n return ImmutableMap.of(\n \"post\",\n ImmutableMap.ofEntries(\n Map.entry(\"summary\", actionDisplayName),\n Map.entry(\"description\", description + \" \" + toolInstructions),\n Map.entry(\"operationId\", toolName + \"_\" + actionDisplayName),\n Map.entry(\"x-action\", action),\n Map.entry(\"x-operation\", operation),\n Map.entry(\n \"requestBody\",\n ImmutableMap.of(\n \"content\",\n ImmutableMap.of(\n \"application/json\",\n ImmutableMap.of(\n \"schema\",\n ImmutableMap.of(\n \"$ref\",\n String.format(\n \"#/components/schemas/%s_Request\", actionDisplayName)))))),\n Map.entry(\n \"responses\",\n ImmutableMap.of(\n \"200\",\n ImmutableMap.of(\n \"description\",\n \"Success response\",\n \"content\",\n ImmutableMap.of(\n \"application/json\",\n ImmutableMap.of(\n \"schema\",\n ImmutableMap.of(\n \"$ref\",\n String.format(\n \"#/components/schemas/%s_Response\",\n actionDisplayName)))))))));\n }\n\n public static ImmutableMap listOperation(\n String entity, String schemaAsString, String toolName, String toolInstructions) {\n return ImmutableMap.of(\n \"post\",\n ImmutableMap.ofEntries(\n Map.entry(\"summary\", \"List \" + entity),\n Map.entry(\n \"description\",\n String.format(\n \"Returns the list of %s data. If the page token was available in the response,\"\n + \" let users know there are more records available. Ask if the user wants\"\n + \" to fetch the next page of results. When passing filter use the\"\n + \" following format: `field_name1='value1' AND field_name2='value2'`. %s\",\n entity, toolInstructions)),\n Map.entry(\"x-operation\", \"LIST_ENTITIES\"),\n Map.entry(\"x-entity\", entity),\n Map.entry(\"operationId\", toolName + \"_list_\" + entity),\n Map.entry(\n \"requestBody\",\n ImmutableMap.of(\n \"content\",\n ImmutableMap.of(\n \"application/json\",\n ImmutableMap.of(\n \"schema\",\n ImmutableMap.of(\n \"$ref\", \"#/components/schemas/list_\" + entity + \"_Request\"))))),\n Map.entry(\n \"responses\",\n ImmutableMap.of(\n \"200\",\n ImmutableMap.of(\n \"description\",\n \"Success response\",\n \"content\",\n ImmutableMap.of(\n \"application/json\",\n ImmutableMap.of(\n \"schema\",\n ImmutableMap.of(\n \"description\",\n String.format(\n \"Returns a list of %s of json schema: %s\",\n entity, schemaAsString),\n \"$ref\",\n \"#/components/schemas/execute-connector_Response\"))))))));\n }\n\n public static ImmutableMap getOperation(\n String entity, String schemaAsString, String toolName, String toolInstructions) {\n return ImmutableMap.of(\n \"post\",\n ImmutableMap.ofEntries(\n Map.entry(\"summary\", \"Get \" + entity),\n Map.entry(\n \"description\",\n String.format(\"Returns the details of the %s. %s\", entity, toolInstructions)),\n Map.entry(\"operationId\", toolName + \"_get_\" + entity),\n Map.entry(\"x-operation\", \"GET_ENTITY\"),\n Map.entry(\"x-entity\", entity),\n Map.entry(\n \"requestBody\",\n ImmutableMap.of(\n \"content\",\n ImmutableMap.of(\n \"application/json\",\n ImmutableMap.of(\n \"schema\",\n ImmutableMap.of(\n \"$ref\", \"#/components/schemas/get_\" + entity + \"_Request\"))))),\n Map.entry(\n \"responses\",\n ImmutableMap.of(\n \"200\",\n ImmutableMap.of(\n \"description\",\n \"Success response\",\n \"content\",\n ImmutableMap.of(\n \"application/json\",\n ImmutableMap.of(\n \"schema\",\n ImmutableMap.of(\n \"description\",\n String.format(\n \"Returns %s of json schema: %s\", entity, schemaAsString),\n \"$ref\",\n \"#/components/schemas/execute-connector_Response\"))))))));\n }\n\n public static ImmutableMap createOperation(\n String entity, String toolName, String toolInstructions) {\n return ImmutableMap.of(\n \"post\",\n ImmutableMap.ofEntries(\n Map.entry(\"summary\", \"Creates a new \" + entity),\n Map.entry(\n \"description\", String.format(\"Creates a new %s. %s\", entity, toolInstructions)),\n Map.entry(\"x-operation\", \"CREATE_ENTITY\"),\n Map.entry(\"x-entity\", entity),\n Map.entry(\"operationId\", toolName + \"_create_\" + entity),\n Map.entry(\n \"requestBody\",\n ImmutableMap.of(\n \"content\",\n ImmutableMap.of(\n \"application/json\",\n ImmutableMap.of(\n \"schema\",\n ImmutableMap.of(\n \"$ref\", \"#/components/schemas/create_\" + entity + \"_Request\"))))),\n Map.entry(\n \"responses\",\n ImmutableMap.of(\n \"200\",\n ImmutableMap.of(\n \"description\",\n \"Success response\",\n \"content\",\n ImmutableMap.of(\n \"application/json\",\n ImmutableMap.of(\n \"schema\",\n ImmutableMap.of(\n \"$ref\",\n \"#/components/schemas/execute-connector_Response\"))))))));\n }\n\n public static ImmutableMap updateOperation(\n String entity, String toolName, String toolInstructions) {\n return ImmutableMap.of(\n \"post\",\n ImmutableMap.ofEntries(\n Map.entry(\"summary\", \"Updates the \" + entity),\n Map.entry(\"description\", String.format(\"Updates the %s. %s\", entity, toolInstructions)),\n Map.entry(\"x-operation\", \"UPDATE_ENTITY\"),\n Map.entry(\"x-entity\", entity),\n Map.entry(\"operationId\", toolName + \"_update_\" + entity),\n Map.entry(\n \"requestBody\",\n ImmutableMap.of(\n \"content\",\n ImmutableMap.of(\n \"application/json\",\n ImmutableMap.of(\n \"schema\",\n ImmutableMap.of(\n \"$ref\", \"#/components/schemas/update_\" + entity + \"_Request\"))))),\n Map.entry(\n \"responses\",\n ImmutableMap.of(\n \"200\",\n ImmutableMap.of(\n \"description\",\n \"Success response\",\n \"content\",\n ImmutableMap.of(\n \"application/json\",\n ImmutableMap.of(\n \"schema\",\n ImmutableMap.of(\n \"$ref\",\n \"#/components/schemas/execute-connector_Response\"))))))));\n }\n\n public static ImmutableMap deleteOperation(\n String entity, String toolName, String toolInstructions) {\n return ImmutableMap.of(\n \"post\",\n ImmutableMap.ofEntries(\n Map.entry(\"summary\", \"Delete the \" + entity),\n Map.entry(\"description\", String.format(\"Deletes the %s. %s\", entity, toolInstructions)),\n Map.entry(\"x-operation\", \"DELETE_ENTITY\"),\n Map.entry(\"x-entity\", entity),\n Map.entry(\"operationId\", toolName + \"_delete_\" + entity),\n Map.entry(\n \"requestBody\",\n ImmutableMap.of(\n \"content\",\n ImmutableMap.of(\n \"application/json\",\n ImmutableMap.of(\n \"schema\",\n ImmutableMap.of(\n \"$ref\", \"#/components/schemas/delete_\" + entity + \"_Request\"))))),\n Map.entry(\n \"responses\",\n ImmutableMap.of(\n \"200\",\n ImmutableMap.of(\n \"description\",\n \"Success response\",\n \"content\",\n ImmutableMap.of(\n \"application/json\",\n ImmutableMap.of(\n \"schema\",\n ImmutableMap.of(\n \"$ref\",\n \"#/components/schemas/execute-connector_Response\"))))))));\n }\n\n public static ImmutableMap createOperationRequest(String entity) {\n return ImmutableMap.of(\n \"type\",\n \"object\",\n \"required\",\n ImmutableList.of(\n \"connectorInputPayload\",\n \"operation\",\n \"connectionName\",\n \"serviceName\",\n \"host\",\n \"entity\"),\n \"properties\",\n ImmutableMap.ofEntries(\n Map.entry(\n \"connectorInputPayload\",\n ImmutableMap.of(\"$ref\", \"#/components/schemas/connectorInputPayload_\" + entity)),\n Map.entry(\"operation\", ImmutableMap.of(\"$ref\", \"#/components/schemas/operation\")),\n Map.entry(\n \"connectionName\", ImmutableMap.of(\"$ref\", \"#/components/schemas/connectionName\")),\n Map.entry(\"serviceName\", ImmutableMap.of(\"$ref\", \"#/components/schemas/serviceName\")),\n Map.entry(\"host\", ImmutableMap.of(\"$ref\", \"#/components/schemas/host\")),\n Map.entry(\"entity\", ImmutableMap.of(\"$ref\", \"#/components/schemas/entity\"))));\n }\n\n public static ImmutableMap updateOperationRequest(String entity) {\n return ImmutableMap.of(\n \"type\",\n \"object\",\n \"required\",\n ImmutableList.of(\n \"connectorInputPayload\",\n \"entityId\",\n \"operation\",\n \"connectionName\",\n \"serviceName\",\n \"host\",\n \"entity\"),\n \"properties\",\n ImmutableMap.ofEntries(\n Map.entry(\n \"connectorInputPayload\",\n ImmutableMap.of(\"$ref\", \"#/components/schemas/connectorInputPayload_\" + entity)),\n Map.entry(\"entityId\", ImmutableMap.of(\"$ref\", \"#/components/schemas/entityId\")),\n Map.entry(\"operation\", ImmutableMap.of(\"$ref\", \"#/components/schemas/operation\")),\n Map.entry(\n \"connectionName\", ImmutableMap.of(\"$ref\", \"#/components/schemas/connectionName\")),\n Map.entry(\"serviceName\", ImmutableMap.of(\"$ref\", \"#/components/schemas/serviceName\")),\n Map.entry(\"host\", ImmutableMap.of(\"$ref\", \"#/components/schemas/host\")),\n Map.entry(\"entity\", ImmutableMap.of(\"$ref\", \"#/components/schemas/entity\")),\n Map.entry(\n \"filterClause\", ImmutableMap.of(\"$ref\", \"#/components/schemas/filterClause\"))));\n }\n\n public static ImmutableMap getOperationRequest() {\n return ImmutableMap.of(\n \"type\",\n \"object\",\n \"required\",\n ImmutableList.of(\n \"entityId\", \"operation\", \"connectionName\", \"serviceName\", \"host\", \"entity\"),\n \"properties\",\n ImmutableMap.ofEntries(\n Map.entry(\"entityId\", ImmutableMap.of(\"$ref\", \"#/components/schemas/entityId\")),\n Map.entry(\"operation\", ImmutableMap.of(\"$ref\", \"#/components/schemas/operation\")),\n Map.entry(\n \"connectionName\", ImmutableMap.of(\"$ref\", \"#/components/schemas/connectionName\")),\n Map.entry(\"serviceName\", ImmutableMap.of(\"$ref\", \"#/components/schemas/serviceName\")),\n Map.entry(\"host\", ImmutableMap.of(\"$ref\", \"#/components/schemas/host\")),\n Map.entry(\"entity\", ImmutableMap.of(\"$ref\", \"#/components/schemas/entity\"))));\n }\n\n public static ImmutableMap deleteOperationRequest() {\n return ImmutableMap.of(\n \"type\",\n \"object\",\n \"required\",\n ImmutableList.of(\n \"entityId\", \"operation\", \"connectionName\", \"serviceName\", \"host\", \"entity\"),\n \"properties\",\n ImmutableMap.ofEntries(\n Map.entry(\"entityId\", ImmutableMap.of(\"$ref\", \"#/components/schemas/entityId\")),\n Map.entry(\"operation\", ImmutableMap.of(\"$ref\", \"#/components/schemas/operation\")),\n Map.entry(\n \"connectionName\", ImmutableMap.of(\"$ref\", \"#/components/schemas/connectionName\")),\n Map.entry(\"serviceName\", ImmutableMap.of(\"$ref\", \"#/components/schemas/serviceName\")),\n Map.entry(\"host\", ImmutableMap.of(\"$ref\", \"#/components/schemas/host\")),\n Map.entry(\"entity\", ImmutableMap.of(\"$ref\", \"#/components/schemas/entity\")),\n Map.entry(\n \"filterClause\", ImmutableMap.of(\"$ref\", \"#/components/schemas/filterClause\"))));\n }\n\n public static ImmutableMap listOperationRequest() {\n return ImmutableMap.of(\n \"type\",\n \"object\",\n \"required\",\n ImmutableList.of(\"operation\", \"connectionName\", \"serviceName\", \"host\", \"entity\"),\n \"properties\",\n ImmutableMap.ofEntries(\n Map.entry(\"filterClause\", ImmutableMap.of(\"$ref\", \"#/components/schemas/filterClause\")),\n Map.entry(\"pageSize\", ImmutableMap.of(\"$ref\", \"#/components/schemas/pageSize\")),\n Map.entry(\"pageToken\", ImmutableMap.of(\"$ref\", \"#/components/schemas/pageToken\")),\n Map.entry(\"operation\", ImmutableMap.of(\"$ref\", \"#/components/schemas/operation\")),\n Map.entry(\n \"connectionName\", ImmutableMap.of(\"$ref\", \"#/components/schemas/connectionName\")),\n Map.entry(\"serviceName\", ImmutableMap.of(\"$ref\", \"#/components/schemas/serviceName\")),\n Map.entry(\"host\", ImmutableMap.of(\"$ref\", \"#/components/schemas/host\")),\n Map.entry(\"entity\", ImmutableMap.of(\"$ref\", \"#/components/schemas/entity\")),\n Map.entry(\n \"sortByColumns\", ImmutableMap.of(\"$ref\", \"#/components/schemas/sortByColumns\"))));\n }\n\n public static ImmutableMap actionRequest(String action) {\n return ImmutableMap.of(\n \"type\",\n \"object\",\n \"required\",\n ImmutableList.of(\n \"operation\",\n \"connectionName\",\n \"serviceName\",\n \"host\",\n \"action\",\n \"connectorInputPayload\"),\n \"properties\",\n ImmutableMap.ofEntries(\n Map.entry(\"operation\", ImmutableMap.of(\"$ref\", \"#/components/schemas/operation\")),\n Map.entry(\n \"connectionName\", ImmutableMap.of(\"$ref\", \"#/components/schemas/connectionName\")),\n Map.entry(\"serviceName\", ImmutableMap.of(\"$ref\", \"#/components/schemas/serviceName\")),\n Map.entry(\"host\", ImmutableMap.of(\"$ref\", \"#/components/schemas/host\")),\n Map.entry(\"action\", ImmutableMap.of(\"$ref\", \"#/components/schemas/action\")),\n Map.entry(\n \"connectorInputPayload\",\n ImmutableMap.of(\"$ref\", \"#/components/schemas/connectorInputPayload_\" + action))));\n }\n\n public static ImmutableMap actionResponse(String action) {\n return ImmutableMap.of(\n \"type\",\n \"object\",\n \"properties\",\n ImmutableMap.of(\n \"connectorOutputPayload\",\n ImmutableMap.of(\"$ref\", \"#/components/schemas/connectorOutputPayload_\" + action)));\n }\n\n public static ImmutableMap executeCustomQueryRequest() {\n return ImmutableMap.of(\n \"type\",\n \"object\",\n \"required\",\n ImmutableList.of(\n \"operation\",\n \"connectionName\",\n \"serviceName\",\n \"host\",\n \"action\",\n \"query\",\n \"timeout\",\n \"pageSize\"),\n \"properties\",\n ImmutableMap.ofEntries(\n Map.entry(\"operation\", ImmutableMap.of(\"$ref\", \"#/components/schemas/operation\")),\n Map.entry(\n \"connectionName\", ImmutableMap.of(\"$ref\", \"#/components/schemas/connectionName\")),\n Map.entry(\"serviceName\", ImmutableMap.of(\"$ref\", \"#/components/schemas/serviceName\")),\n Map.entry(\"host\", ImmutableMap.of(\"$ref\", \"#/components/schemas/host\")),\n Map.entry(\"action\", ImmutableMap.of(\"$ref\", \"#/components/schemas/action\")),\n Map.entry(\"query\", ImmutableMap.of(\"$ref\", \"#/components/schemas/query\")),\n Map.entry(\"timeout\", ImmutableMap.of(\"$ref\", \"#/components/schemas/timeout\")),\n Map.entry(\"pageSize\", ImmutableMap.of(\"$ref\", \"#/components/schemas/pageSize\"))));\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/agents/BaseAgent.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.agents;\n\nimport static com.google.common.collect.ImmutableList.toImmutableList;\n\nimport com.google.adk.Telemetry;\nimport com.google.adk.agents.Callbacks.AfterAgentCallback;\nimport com.google.adk.agents.Callbacks.BeforeAgentCallback;\nimport com.google.adk.events.Event;\nimport com.google.common.collect.ImmutableList;\nimport com.google.genai.types.Content;\nimport io.opentelemetry.api.trace.Span;\nimport io.opentelemetry.api.trace.Tracer;\nimport io.opentelemetry.context.Scope;\nimport io.reactivex.rxjava3.core.Flowable;\nimport io.reactivex.rxjava3.core.Maybe;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.function.Function;\nimport org.jspecify.annotations.Nullable;\n\n/** Base class for all agents. */\npublic abstract class BaseAgent {\n\n /** The agent's name. Must be a unique identifier within the agent tree. */\n private final String name;\n\n /**\n * One line description about the agent's capability. The system can use this for decision-making\n * when delegating control to different agents.\n */\n private final String description;\n\n /**\n * The parent agent in the agent tree. Note that one agent cannot be added to two different\n * parents' sub-agents lists.\n */\n private BaseAgent parentAgent;\n\n private final List subAgents;\n\n private final Optional> beforeAgentCallback;\n private final Optional> afterAgentCallback;\n\n /**\n * Creates a new BaseAgent.\n *\n * @param name Unique agent name. Cannot be \"user\" (reserved).\n * @param description Agent purpose.\n * @param subAgents Agents managed by this agent.\n * @param beforeAgentCallback Callbacks before agent execution. Invoked in order until one doesn't\n * return null.\n * @param afterAgentCallback Callbacks after agent execution. Invoked in order until one doesn't\n * return null.\n */\n public BaseAgent(\n String name,\n String description,\n List subAgents,\n List beforeAgentCallback,\n List afterAgentCallback) {\n this.name = name;\n this.description = description;\n this.parentAgent = null;\n this.subAgents = subAgents != null ? subAgents : ImmutableList.of();\n this.beforeAgentCallback = Optional.ofNullable(beforeAgentCallback);\n this.afterAgentCallback = Optional.ofNullable(afterAgentCallback);\n\n // Establish parent relationships for all sub-agents if needed.\n for (BaseAgent subAgent : this.subAgents) {\n subAgent.parentAgent(this);\n }\n }\n\n /**\n * Gets the agent's unique name.\n *\n * @return the unique name of the agent.\n */\n public final String name() {\n return name;\n }\n\n /**\n * Gets the one-line description of the agent's capability.\n *\n * @return the description of the agent.\n */\n public final String description() {\n return description;\n }\n\n /**\n * Retrieves the parent agent in the agent tree.\n *\n * @return the parent agent, or {@code null} if this agent does not have a parent.\n */\n public BaseAgent parentAgent() {\n return parentAgent;\n }\n\n /**\n * Sets the parent agent.\n *\n * @param parentAgent The parent agent to set.\n */\n protected void parentAgent(BaseAgent parentAgent) {\n this.parentAgent = parentAgent;\n }\n\n /**\n * Returns the root agent for this agent by traversing up the parent chain.\n *\n * @return the root agent.\n */\n public BaseAgent rootAgent() {\n BaseAgent agent = this;\n while (agent.parentAgent() != null) {\n agent = agent.parentAgent();\n }\n return agent;\n }\n\n /**\n * Finds an agent (this or descendant) by name.\n *\n * @return the agent or descendant with the given name, or {@code null} if not found.\n */\n public BaseAgent findAgent(String name) {\n if (this.name().equals(name)) {\n return this;\n }\n return findSubAgent(name);\n }\n\n /** Recursively search sub agent by name. */\n public @Nullable BaseAgent findSubAgent(String name) {\n for (BaseAgent subAgent : subAgents) {\n if (subAgent.name().equals(name)) {\n return subAgent;\n }\n BaseAgent result = subAgent.findSubAgent(name);\n if (result != null) {\n return result;\n }\n }\n return null;\n }\n\n public List subAgents() {\n return subAgents;\n }\n\n public Optional> beforeAgentCallback() {\n return beforeAgentCallback;\n }\n\n public Optional> afterAgentCallback() {\n return afterAgentCallback;\n }\n\n /**\n * Creates a shallow copy of the parent context with the agent properly being set to this\n * instance.\n *\n * @param parentContext Parent context to copy.\n * @return new context with updated branch name.\n */\n private InvocationContext createInvocationContext(InvocationContext parentContext) {\n InvocationContext invocationContext = InvocationContext.copyOf(parentContext);\n invocationContext.agent(this);\n // Check for branch to be truthy (not None, not empty string),\n if (parentContext.branch().filter(s -> !s.isEmpty()).isPresent()) {\n invocationContext.branch(parentContext.branch().get() + \".\" + name());\n }\n return invocationContext;\n }\n\n /**\n * Runs the agent asynchronously.\n *\n * @param parentContext Parent context to inherit.\n * @return stream of agent-generated events.\n */\n public Flowable runAsync(InvocationContext parentContext) {\n Tracer tracer = Telemetry.getTracer();\n return Flowable.defer(\n () -> {\n Span span = tracer.spanBuilder(\"agent_run [\" + name() + \"]\").startSpan();\n try (Scope scope = span.makeCurrent()) {\n InvocationContext invocationContext = createInvocationContext(parentContext);\n\n Flowable executionFlowable =\n beforeAgentCallback\n .map(\n callback ->\n callCallback(beforeCallbacksToFunctions(callback), invocationContext))\n .orElse(Single.just(Optional.empty()))\n .flatMapPublisher(\n beforeEventOpt -> {\n if (invocationContext.endInvocation()) {\n return Flowable.fromOptional(beforeEventOpt);\n }\n\n Flowable beforeEvents = Flowable.fromOptional(beforeEventOpt);\n Flowable mainEvents =\n Flowable.defer(() -> runAsyncImpl(invocationContext));\n Flowable afterEvents =\n afterAgentCallback\n .map(\n callback ->\n Flowable.defer(\n () ->\n callCallback(\n afterCallbacksToFunctions(callback),\n invocationContext)\n .flatMapPublisher(Flowable::fromOptional)))\n .orElse(Flowable.empty());\n\n return Flowable.concat(beforeEvents, mainEvents, afterEvents);\n });\n return executionFlowable.doFinally(span::end);\n }\n });\n }\n\n /**\n * Converts before-agent callbacks to functions.\n *\n * @param callbacks Before-agent callbacks.\n * @return callback functions.\n */\n private ImmutableList>> beforeCallbacksToFunctions(\n List callbacks) {\n return callbacks.stream()\n .map(callback -> (Function>) callback::call)\n .collect(toImmutableList());\n }\n\n /**\n * Converts after-agent callbacks to functions.\n *\n * @param callbacks After-agent callbacks.\n * @return callback functions.\n */\n private ImmutableList>> afterCallbacksToFunctions(\n List callbacks) {\n return callbacks.stream()\n .map(callback -> (Function>) callback::call)\n .collect(toImmutableList());\n }\n\n /**\n * Calls agent callbacks and returns the first produced event, if any.\n *\n * @param agentCallbacks Callback functions.\n * @param invocationContext Current invocation context.\n * @return single emitting first event, or empty if none.\n */\n private Single> callCallback(\n List>> agentCallbacks,\n InvocationContext invocationContext) {\n if (agentCallbacks == null || agentCallbacks.isEmpty()) {\n return Single.just(Optional.empty());\n }\n\n CallbackContext callbackContext =\n new CallbackContext(invocationContext, /* eventActions= */ null);\n\n return Flowable.fromIterable(agentCallbacks)\n .concatMap(\n callback -> {\n Maybe maybeContent = callback.apply(callbackContext);\n\n return maybeContent\n .map(\n content -> {\n Event.Builder eventBuilder =\n Event.builder()\n .id(Event.generateEventId())\n .invocationId(invocationContext.invocationId())\n .author(name())\n .branch(invocationContext.branch())\n .actions(callbackContext.eventActions());\n\n eventBuilder.content(Optional.of(content));\n invocationContext.setEndInvocation(true);\n return Optional.of(eventBuilder.build());\n })\n .toFlowable();\n })\n .firstElement()\n .switchIfEmpty(\n Single.defer(\n () -> {\n if (callbackContext.state().hasDelta()) {\n Event.Builder eventBuilder =\n Event.builder()\n .id(Event.generateEventId())\n .invocationId(invocationContext.invocationId())\n .author(name())\n .branch(invocationContext.branch())\n .actions(callbackContext.eventActions());\n\n return Single.just(Optional.of(eventBuilder.build()));\n } else {\n return Single.just(Optional.empty());\n }\n }));\n }\n\n /**\n * Runs the agent synchronously.\n *\n * @param parentContext Parent context to inherit.\n * @return stream of agent-generated events.\n */\n public Flowable runLive(InvocationContext parentContext) {\n Tracer tracer = Telemetry.getTracer();\n return Flowable.defer(\n () -> {\n Span span = tracer.spanBuilder(\"agent_run [\" + name() + \"]\").startSpan();\n try (Scope scope = span.makeCurrent()) {\n InvocationContext invocationContext = createInvocationContext(parentContext);\n Flowable executionFlowable = runLiveImpl(invocationContext);\n return executionFlowable.doFinally(span::end);\n }\n });\n }\n\n /**\n * Agent-specific asynchronous logic.\n *\n * @param invocationContext Current invocation context.\n * @return stream of agent-generated events.\n */\n protected abstract Flowable runAsyncImpl(InvocationContext invocationContext);\n\n /**\n * Agent-specific synchronous logic.\n *\n * @param invocationContext Current invocation context.\n * @return stream of agent-generated events.\n */\n protected abstract Flowable runLiveImpl(InvocationContext invocationContext);\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/sessions/VertexAiSessionService.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\nimport static com.google.common.base.Strings.nullToEmpty;\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static java.util.stream.Collectors.toCollection;\n\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.google.adk.JsonBaseModel;\nimport com.google.adk.events.Event;\nimport com.google.adk.events.EventActions;\nimport com.google.auth.oauth2.GoogleCredentials;\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.FinishReason;\nimport com.google.genai.types.GroundingMetadata;\nimport com.google.genai.types.HttpOptions;\nimport com.google.genai.types.Part;\nimport io.reactivex.rxjava3.core.Completable;\nimport io.reactivex.rxjava3.core.Maybe;\nimport io.reactivex.rxjava3.core.Single;\nimport java.io.IOException;\nimport java.io.UncheckedIOException;\nimport java.time.Instant;\nimport java.util.ArrayList;\nimport java.util.Comparator;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentMap;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport javax.annotation.Nullable;\nimport okhttp3.ResponseBody;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/** Connects to the managed Vertex AI Session Service. */\n/** TODO: Use the genai HttpApiClient and ApiResponse methods once they are public. */\npublic final class VertexAiSessionService implements BaseSessionService {\n private static final int MAX_RETRY_ATTEMPTS = 5;\n private static final ObjectMapper objectMapper = JsonBaseModel.getMapper();\n private static final Logger logger = LoggerFactory.getLogger(VertexAiSessionService.class);\n\n private final HttpApiClient apiClient;\n\n /**\n * Creates a new instance of the Vertex AI Session Service with a custom ApiClient for testing.\n */\n public VertexAiSessionService(String project, String location, HttpApiClient apiClient) {\n this.apiClient = apiClient;\n }\n\n /** Creates a session service with default configuration. */\n public VertexAiSessionService() {\n this.apiClient =\n new HttpApiClient(Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty());\n }\n\n /** Creates a session service with specified project, location, credentials, and HTTP options. */\n public VertexAiSessionService(\n String project,\n String location,\n Optional credentials,\n Optional httpOptions) {\n this.apiClient =\n new HttpApiClient(Optional.of(project), Optional.of(location), credentials, httpOptions);\n }\n\n /**\n * Parses the JSON response body from the given API response.\n *\n * @throws UncheckedIOException if parsing fails.\n */\n private static JsonNode getJsonResponse(ApiResponse apiResponse) {\n try {\n ResponseBody responseBody = apiResponse.getResponseBody();\n return objectMapper.readTree(responseBody.string());\n } catch (IOException e) {\n throw new UncheckedIOException(e);\n }\n }\n\n @Override\n public Single createSession(\n String appName,\n String userId,\n @Nullable ConcurrentMap state,\n @Nullable String sessionId) {\n\n String reasoningEngineId = parseReasoningEngineId(appName);\n ConcurrentHashMap sessionJsonMap = new ConcurrentHashMap<>();\n sessionJsonMap.put(\"userId\", userId);\n if (state != null) {\n sessionJsonMap.put(\"sessionState\", state);\n }\n\n ApiResponse apiResponse;\n try {\n apiResponse =\n apiClient.request(\n \"POST\",\n \"reasoningEngines/\" + reasoningEngineId + \"/sessions\",\n objectMapper.writeValueAsString(sessionJsonMap));\n } catch (IOException e) {\n throw new UncheckedIOException(e);\n }\n\n logger.debug(\"Create Session response {}\", apiResponse.getResponseBody());\n String sessionName = \"\";\n String operationId = \"\";\n String sessId = nullToEmpty(sessionId);\n if (apiResponse.getResponseBody() != null) {\n JsonNode jsonResponse = getJsonResponse(apiResponse);\n sessionName = jsonResponse.get(\"name\").asText();\n List parts = Splitter.on('/').splitToList(sessionName);\n sessId = parts.get(parts.size() - 3);\n operationId = Iterables.getLast(parts);\n }\n for (int i = 0; i < MAX_RETRY_ATTEMPTS; i++) {\n ApiResponse lroResponse = apiClient.request(\"GET\", \"operations/\" + operationId, \"\");\n JsonNode jsonResponse = getJsonResponse(lroResponse);\n if (jsonResponse.get(\"done\") != null) {\n break;\n }\n try {\n SECONDS.sleep(1);\n } catch (InterruptedException e) {\n logger.warn(\"Error during sleep\", e);\n }\n }\n\n ApiResponse getSessionApiResponse =\n apiClient.request(\n \"GET\", \"reasoningEngines/\" + reasoningEngineId + \"/sessions/\" + sessId, \"\");\n JsonNode getSessionResponseMap = getJsonResponse(getSessionApiResponse);\n Instant updateTimestamp = Instant.parse(getSessionResponseMap.get(\"updateTime\").asText());\n ConcurrentMap sessionState = null;\n if (getSessionResponseMap != null && getSessionResponseMap.has(\"sessionState\")) {\n JsonNode sessionStateNode = getSessionResponseMap.get(\"sessionState\");\n if (sessionStateNode != null) {\n sessionState =\n objectMapper.convertValue(\n sessionStateNode, new TypeReference>() {});\n }\n }\n return Single.just(\n Session.builder(sessId)\n .appName(appName)\n .userId(userId)\n .lastUpdateTime(updateTimestamp)\n .state(sessionState == null ? new ConcurrentHashMap<>() : sessionState)\n .build());\n }\n\n @Override\n public Single listSessions(String appName, String userId) {\n String reasoningEngineId = parseReasoningEngineId(appName);\n\n ApiResponse apiResponse =\n apiClient.request(\n \"GET\",\n \"reasoningEngines/\" + reasoningEngineId + \"/sessions?filter=user_id=\" + userId,\n \"\");\n\n // Handles empty response case\n if (apiResponse.getResponseBody() == null) {\n return Single.just(ListSessionsResponse.builder().build());\n }\n\n JsonNode listSessionsResponseMap = getJsonResponse(apiResponse);\n List> apiSessions =\n objectMapper.convertValue(\n listSessionsResponseMap.get(\"sessions\"),\n new TypeReference>>() {});\n\n List sessions = new ArrayList<>();\n for (Map apiSession : apiSessions) {\n String sessionId =\n Iterables.getLast(Splitter.on('/').splitToList((String) apiSession.get(\"name\")));\n Instant updateTimestamp = Instant.parse((String) apiSession.get(\"updateTime\"));\n Session session =\n Session.builder(sessionId)\n .appName(appName)\n .userId(userId)\n .state(new ConcurrentHashMap<>())\n .lastUpdateTime(updateTimestamp)\n .build();\n sessions.add(session);\n }\n return Single.just(ListSessionsResponse.builder().sessions(sessions).build());\n }\n\n @Override\n public Single listEvents(String appName, String userId, String sessionId) {\n String reasoningEngineId = parseReasoningEngineId(appName);\n ApiResponse apiResponse =\n apiClient.request(\n \"GET\",\n \"reasoningEngines/\" + reasoningEngineId + \"/sessions/\" + sessionId + \"/events\",\n \"\");\n\n logger.debug(\"List events response {}\", apiResponse);\n\n if (apiResponse.getResponseBody() == null) {\n return Single.just(ListEventsResponse.builder().build());\n }\n\n JsonNode sessionEventsNode = getJsonResponse(apiResponse).get(\"sessionEvents\");\n if (sessionEventsNode == null || sessionEventsNode.isEmpty()) {\n return Single.just(ListEventsResponse.builder().events(new ArrayList<>()).build());\n }\n return Single.just(\n ListEventsResponse.builder()\n .events(\n objectMapper\n .convertValue(\n sessionEventsNode,\n new TypeReference>>() {})\n .stream()\n .map(event -> fromApiEvent(event))\n .collect(toCollection(ArrayList::new)))\n .build());\n }\n\n @Override\n public Maybe getSession(\n String appName, String userId, String sessionId, Optional config) {\n String reasoningEngineId = parseReasoningEngineId(appName);\n ApiResponse apiResponse =\n apiClient.request(\n \"GET\", \"reasoningEngines/\" + reasoningEngineId + \"/sessions/\" + sessionId, \"\");\n JsonNode getSessionResponseMap = getJsonResponse(apiResponse);\n\n if (getSessionResponseMap == null) {\n return Maybe.empty();\n }\n\n String sessId =\n Optional.ofNullable(getSessionResponseMap.get(\"name\"))\n .map(name -> Iterables.getLast(Splitter.on('/').splitToList(name.asText())))\n .orElse(sessionId);\n Instant updateTimestamp =\n Optional.ofNullable(getSessionResponseMap.get(\"updateTime\"))\n .map(updateTime -> Instant.parse(updateTime.asText()))\n .orElse(null);\n\n ConcurrentMap sessionState = new ConcurrentHashMap<>();\n if (getSessionResponseMap != null && getSessionResponseMap.has(\"sessionState\")) {\n sessionState.putAll(\n objectMapper.convertValue(\n getSessionResponseMap.get(\"sessionState\"),\n new TypeReference>() {}));\n }\n\n return listEvents(appName, userId, sessionId)\n .map(\n response -> {\n Session.Builder sessionBuilder =\n Session.builder(sessId)\n .appName(appName)\n .userId(userId)\n .lastUpdateTime(updateTimestamp)\n .state(sessionState);\n List events = response.events();\n if (events.isEmpty()) {\n return sessionBuilder.build();\n }\n events =\n events.stream()\n .filter(\n event ->\n updateTimestamp == null\n || Instant.ofEpochMilli(event.timestamp())\n .isBefore(updateTimestamp))\n .sorted(Comparator.comparing(Event::timestamp))\n .collect(toCollection(ArrayList::new));\n\n if (config.isPresent()) {\n if (config.get().numRecentEvents().isPresent()) {\n int numRecentEvents = config.get().numRecentEvents().get();\n if (events.size() > numRecentEvents) {\n events = events.subList(events.size() - numRecentEvents, events.size());\n }\n } else if (config.get().afterTimestamp().isPresent()) {\n Instant afterTimestamp = config.get().afterTimestamp().get();\n int i = events.size() - 1;\n while (i >= 0) {\n if (Instant.ofEpochMilli(events.get(i).timestamp()).isBefore(afterTimestamp)) {\n break;\n }\n i -= 1;\n }\n if (i >= 0) {\n events = events.subList(i, events.size());\n }\n }\n }\n return sessionBuilder.events(events).build();\n })\n .toMaybe();\n }\n\n @Override\n public Completable deleteSession(String appName, String userId, String sessionId) {\n String reasoningEngineId = parseReasoningEngineId(appName);\n ApiResponse unused =\n apiClient.request(\n \"DELETE\", \"reasoningEngines/\" + reasoningEngineId + \"/sessions/\" + sessionId, \"\");\n return Completable.complete();\n }\n\n @Override\n public Single appendEvent(Session session, Event event) {\n BaseSessionService.super.appendEvent(session, event);\n\n String reasoningEngineId = parseReasoningEngineId(session.appName());\n ApiResponse response =\n apiClient.request(\n \"POST\",\n \"reasoningEngines/\" + reasoningEngineId + \"/sessions/\" + session.id() + \":appendEvent\",\n convertEventToJson(event));\n // TODO(b/414263934)): Improve error handling for appendEvent.\n try {\n if (response.getResponseBody().string().contains(\"com.google.genai.errors.ClientException\")) {\n logger.warn(\"Failed to append event: \", event);\n }\n } catch (IOException e) {\n throw new UncheckedIOException(e);\n }\n\n response.close();\n return Single.just(event);\n }\n\n /**\n * Converts an {@link Event} to its JSON string representation for API transmission.\n *\n * @return JSON string of the event.\n * @throws UncheckedIOException if serialization fails.\n */\n static String convertEventToJson(Event event) {\n Map metadataJson = new HashMap<>();\n metadataJson.put(\"partial\", event.partial());\n metadataJson.put(\"turnComplete\", event.turnComplete());\n metadataJson.put(\"interrupted\", event.interrupted());\n metadataJson.put(\"branch\", event.branch().orElse(null));\n metadataJson.put(\n \"long_running_tool_ids\",\n event.longRunningToolIds() != null ? event.longRunningToolIds().orElse(null) : null);\n if (event.groundingMetadata() != null) {\n metadataJson.put(\"grounding_metadata\", event.groundingMetadata());\n }\n\n Map eventJson = new HashMap<>();\n eventJson.put(\"author\", event.author());\n eventJson.put(\"invocationId\", event.invocationId());\n eventJson.put(\n \"timestamp\",\n new HashMap<>(\n ImmutableMap.of(\n \"seconds\",\n event.timestamp() / 1000,\n \"nanos\",\n (event.timestamp() % 1000) * 1000000)));\n if (event.errorCode().isPresent()) {\n eventJson.put(\"errorCode\", event.errorCode());\n }\n if (event.errorMessage().isPresent()) {\n eventJson.put(\"errorMessage\", event.errorMessage());\n }\n eventJson.put(\"eventMetadata\", metadataJson);\n\n if (event.actions() != null) {\n Map actionsJson = new HashMap<>();\n actionsJson.put(\"skipSummarization\", event.actions().skipSummarization());\n actionsJson.put(\"stateDelta\", event.actions().stateDelta());\n actionsJson.put(\"artifactDelta\", event.actions().artifactDelta());\n actionsJson.put(\"transferAgent\", event.actions().transferToAgent());\n actionsJson.put(\"escalate\", event.actions().escalate());\n actionsJson.put(\"requestedAuthConfigs\", event.actions().requestedAuthConfigs());\n eventJson.put(\"actions\", actionsJson);\n }\n if (event.content().isPresent()) {\n eventJson.put(\"content\", SessionUtils.encodeContent(event.content().get()));\n }\n if (event.errorCode().isPresent()) {\n eventJson.put(\"errorCode\", event.errorCode().get());\n }\n if (event.errorMessage().isPresent()) {\n eventJson.put(\"errorMessage\", event.errorMessage().get());\n }\n try {\n return objectMapper.writeValueAsString(eventJson);\n } catch (JsonProcessingException e) {\n throw new UncheckedIOException(e);\n }\n }\n\n /**\n * Converts a raw value to a {@link Content} object.\n *\n * @return parsed {@link Content}, or {@code null} if conversion fails.\n */\n @Nullable\n @SuppressWarnings(\"unchecked\")\n private static Content convertMapToContent(Object rawContentValue) {\n if (rawContentValue == null) {\n return null;\n }\n\n if (rawContentValue instanceof Map) {\n Map contentMap = (Map) rawContentValue;\n try {\n return objectMapper.convertValue(contentMap, Content.class);\n } catch (IllegalArgumentException e) {\n logger.warn(\"Error converting Map to Content\", e);\n return null;\n }\n } else {\n logger.warn(\n \"Unexpected type for 'content' in apiEvent: {}\", rawContentValue.getClass().getName());\n return null;\n }\n }\n\n /**\n * Extracts the reasoning engine ID from the given app name or full resource name.\n *\n * @return reasoning engine ID.\n * @throws IllegalArgumentException if format is invalid.\n */\n static String parseReasoningEngineId(String appName) {\n if (appName.matches(\"\\\\d+\")) {\n return appName;\n }\n\n Matcher matcher = APP_NAME_PATTERN.matcher(appName);\n\n if (!matcher.matches()) {\n throw new IllegalArgumentException(\n \"App name \"\n + appName\n + \" is not valid. It should either be the full\"\n + \" ReasoningEngine resource name, or the reasoning engine id.\");\n }\n\n return matcher.group(matcher.groupCount());\n }\n\n /**\n * Converts raw API event data into an {@link Event} object.\n *\n * @return parsed {@link Event}.\n */\n @SuppressWarnings(\"unchecked\")\n static Event fromApiEvent(Map apiEvent) {\n EventActions eventActions = new EventActions();\n if (apiEvent.get(\"actions\") != null) {\n Map actionsMap = (Map) apiEvent.get(\"actions\");\n eventActions.setSkipSummarization(\n Optional.ofNullable(actionsMap.get(\"skipSummarization\")).map(value -> (Boolean) value));\n eventActions.setStateDelta(\n actionsMap.get(\"stateDelta\") != null\n ? new ConcurrentHashMap<>((Map) actionsMap.get(\"stateDelta\"))\n : new ConcurrentHashMap<>());\n eventActions.setArtifactDelta(\n actionsMap.get(\"artifactDelta\") != null\n ? new ConcurrentHashMap<>((Map) actionsMap.get(\"artifactDelta\"))\n : new ConcurrentHashMap<>());\n eventActions.setTransferToAgent(\n actionsMap.get(\"transferAgent\") != null\n ? (String) actionsMap.get(\"transferAgent\")\n : null);\n eventActions.setEscalate(\n Optional.ofNullable(actionsMap.get(\"escalate\")).map(value -> (Boolean) value));\n eventActions.setRequestedAuthConfigs(\n Optional.ofNullable(actionsMap.get(\"requestedAuthConfigs\"))\n .map(VertexAiSessionService::asConcurrentMapOfConcurrentMaps)\n .orElse(new ConcurrentHashMap<>()));\n }\n\n Event event =\n Event.builder()\n .id((String) Iterables.getLast(Splitter.on('/').split(apiEvent.get(\"name\").toString())))\n .invocationId((String) apiEvent.get(\"invocationId\"))\n .author((String) apiEvent.get(\"author\"))\n .actions(eventActions)\n .content(\n Optional.ofNullable(apiEvent.get(\"content\"))\n .map(VertexAiSessionService::convertMapToContent)\n .map(SessionUtils::decodeContent)\n .orElse(null))\n .timestamp(convertToInstant(apiEvent.get(\"timestamp\")).toEpochMilli())\n .errorCode(\n Optional.ofNullable(apiEvent.get(\"errorCode\"))\n .map(value -> new FinishReason((String) value)))\n .errorMessage(\n Optional.ofNullable(apiEvent.get(\"errorMessage\")).map(value -> (String) value))\n .branch(Optional.ofNullable(apiEvent.get(\"branch\")).map(value -> (String) value))\n .build();\n // TODO(b/414263934): Add Event branch and grounding metadata for python parity.\n if (apiEvent.get(\"eventMetadata\") != null) {\n Map eventMetadata = (Map) apiEvent.get(\"eventMetadata\");\n List longRunningToolIdsList = (List) eventMetadata.get(\"longRunningToolIds\");\n\n GroundingMetadata groundingMetadata = null;\n Object rawGroundingMetadata = eventMetadata.get(\"groundingMetadata\");\n if (rawGroundingMetadata != null) {\n groundingMetadata =\n objectMapper.convertValue(rawGroundingMetadata, GroundingMetadata.class);\n }\n\n event =\n event.toBuilder()\n .partial(Optional.ofNullable((Boolean) eventMetadata.get(\"partial\")).orElse(false))\n .turnComplete(\n Optional.ofNullable((Boolean) eventMetadata.get(\"turnComplete\")).orElse(false))\n .interrupted(\n Optional.ofNullable((Boolean) eventMetadata.get(\"interrupted\")).orElse(false))\n .branch(Optional.ofNullable((String) eventMetadata.get(\"branch\")))\n .groundingMetadata(groundingMetadata)\n .longRunningToolIds(\n longRunningToolIdsList != null ? new HashSet<>(longRunningToolIdsList) : null)\n .build();\n }\n return event;\n }\n\n /**\n * Converts a timestamp from a Map or String into an {@link Instant}.\n *\n * @param timestampObj map with \"seconds\"/\"nanos\" or an ISO string.\n * @return parsed {@link Instant}.\n */\n private static Instant convertToInstant(Object timestampObj) {\n if (timestampObj instanceof Map timestampMap) {\n return Instant.ofEpochSecond(\n ((Number) timestampMap.get(\"seconds\")).longValue(),\n ((Number) timestampMap.get(\"nanos\")).longValue());\n } else if (timestampObj != null) {\n return Instant.parse(timestampObj.toString());\n } else {\n throw new IllegalArgumentException(\"Timestamp not found in apiEvent\");\n }\n }\n\n /**\n * Converts a nested map into a {@link ConcurrentMap} of {@link ConcurrentMap}s.\n *\n * @return thread-safe nested map.\n */\n @SuppressWarnings(\"unchecked\")\n private static ConcurrentMap>\n asConcurrentMapOfConcurrentMaps(Object value) {\n return ((Map>) value)\n .entrySet().stream()\n .collect(\n ConcurrentHashMap::new,\n (map, entry) -> map.put(entry.getKey(), new ConcurrentHashMap<>(entry.getValue())),\n ConcurrentHashMap::putAll);\n }\n\n /** Regex for parsing full ReasoningEngine resource names. */\n private static final Pattern APP_NAME_PATTERN =\n Pattern.compile(\n \"^projects/([a-zA-Z0-9-_]+)/locations/([a-zA-Z0-9-_]+)/reasoningEngines/(\\\\d+)$\");\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/events/Event.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.events;\n\nimport static com.google.common.collect.ImmutableList.toImmutableList;\n\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonIgnore;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.databind.annotation.JsonDeserialize;\nimport com.google.adk.JsonBaseModel;\nimport com.google.common.collect.ImmutableList;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.FinishReason;\nimport com.google.genai.types.FunctionCall;\nimport com.google.genai.types.FunctionResponse;\nimport com.google.genai.types.GroundingMetadata;\nimport java.time.Instant;\nimport java.util.List;\nimport java.util.Objects;\nimport java.util.Optional;\nimport java.util.Set;\nimport java.util.UUID;\nimport javax.annotation.Nullable;\n\n// TODO - b/413761119 update Agent.java when resolved.\n/** Represents an event in a session. */\n@JsonDeserialize(builder = Event.Builder.class)\npublic class Event extends JsonBaseModel {\n\n private String id;\n private String invocationId;\n private String author;\n private Optional content = Optional.empty();\n private EventActions actions;\n private Optional> longRunningToolIds = Optional.empty();\n private Optional partial = Optional.empty();\n private Optional turnComplete = Optional.empty();\n private Optional errorCode = Optional.empty();\n private Optional errorMessage = Optional.empty();\n private Optional interrupted = Optional.empty();\n private Optional branch = Optional.empty();\n private Optional groundingMetadata = Optional.empty();\n private long timestamp;\n\n private Event() {}\n\n public static String generateEventId() {\n return UUID.randomUUID().toString();\n }\n\n /** The event id. */\n @JsonProperty(\"id\")\n public String id() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n /** Id of the invocation that this event belongs to. */\n @JsonProperty(\"invocationId\")\n public String invocationId() {\n return invocationId;\n }\n\n public void setInvocationId(String invocationId) {\n this.invocationId = invocationId;\n }\n\n /** The author of the event, it could be the name of the agent or \"user\" literal. */\n @JsonProperty(\"author\")\n public String author() {\n return author;\n }\n\n public void setAuthor(String author) {\n this.author = author;\n }\n\n @JsonProperty(\"content\")\n public Optional content() {\n return content;\n }\n\n public void setContent(Optional content) {\n this.content = content;\n }\n\n @JsonProperty(\"actions\")\n public EventActions actions() {\n return actions;\n }\n\n public void setActions(EventActions actions) {\n this.actions = actions;\n }\n\n /**\n * Set of ids of the long running function calls. Agent client will know from this field about\n * which function call is long running.\n */\n @JsonProperty(\"longRunningToolIds\")\n public Optional> longRunningToolIds() {\n return longRunningToolIds;\n }\n\n public void setLongRunningToolIds(Optional> longRunningToolIds) {\n this.longRunningToolIds = longRunningToolIds;\n }\n\n /**\n * partial is true for incomplete chunks from the LLM streaming response. The last chunk's partial\n * is False.\n */\n @JsonProperty(\"partial\")\n public Optional partial() {\n return partial;\n }\n\n public void setPartial(Optional partial) {\n this.partial = partial;\n }\n\n @JsonProperty(\"turnComplete\")\n public Optional turnComplete() {\n return turnComplete;\n }\n\n public void setTurnComplete(Optional turnComplete) {\n this.turnComplete = turnComplete;\n }\n\n @JsonProperty(\"errorCode\")\n public Optional errorCode() {\n return errorCode;\n }\n\n public void setErrorCode(Optional errorCode) {\n this.errorCode = errorCode;\n }\n\n @JsonProperty(\"errorMessage\")\n public Optional errorMessage() {\n return errorMessage;\n }\n\n public void setErrorMessage(Optional errorMessage) {\n this.errorMessage = errorMessage;\n }\n\n @JsonProperty(\"interrupted\")\n public Optional interrupted() {\n return interrupted;\n }\n\n public void setInterrupted(Optional interrupted) {\n this.interrupted = interrupted;\n }\n\n /**\n * The branch of the event. The format is like agent_1.agent_2.agent_3, where agent_1 is the\n * parent of agent_2, and agent_2 is the parent of agent_3. Branch is used when multiple sub-agent\n * shouldn't see their peer agents' conversation history.\n */\n @JsonProperty(\"branch\")\n public Optional branch() {\n return branch;\n }\n\n /**\n * Sets the branch for this event.\n *\n *

Format: agentA.agentB.agentC — shows hierarchy of nested agents.\n *\n * @param branch Branch identifier.\n */\n public void branch(@Nullable String branch) {\n this.branch = Optional.ofNullable(branch);\n }\n\n public void branch(Optional branch) {\n this.branch = branch;\n }\n\n /** The grounding metadata of the event. */\n @JsonProperty(\"groundingMetadata\")\n public Optional groundingMetadata() {\n return groundingMetadata;\n }\n\n public void setGroundingMetadata(Optional groundingMetadata) {\n this.groundingMetadata = groundingMetadata;\n }\n\n /** The timestamp of the event. */\n @JsonProperty(\"timestamp\")\n public long timestamp() {\n return timestamp;\n }\n\n public void setTimestamp(long timestamp) {\n this.timestamp = timestamp;\n }\n\n /** Returns all function calls from this event. */\n @JsonIgnore\n public final ImmutableList functionCalls() {\n return content().flatMap(Content::parts).stream()\n .flatMap(List::stream)\n .flatMap(part -> part.functionCall().stream())\n .collect(toImmutableList());\n }\n\n /** Returns all function responses from this event. */\n @JsonIgnore\n public final ImmutableList functionResponses() {\n return content().flatMap(Content::parts).stream()\n .flatMap(List::stream)\n .flatMap(part -> part.functionResponse().stream())\n .collect(toImmutableList());\n }\n\n /** Returns true if this is a final response. */\n @JsonIgnore\n public final boolean finalResponse() {\n if (actions().skipSummarization().orElse(false)\n || (longRunningToolIds().isPresent() && !longRunningToolIds().get().isEmpty())) {\n return true;\n }\n return functionCalls().isEmpty() && functionResponses().isEmpty() && !partial().orElse(false);\n }\n\n /**\n * Converts the event content into a readable string.\n *\n *

Includes text, function calls, and responses.\n *\n * @return Stringified content.\n */\n public final String stringifyContent() {\n StringBuilder sb = new StringBuilder();\n content().flatMap(Content::parts).stream()\n .flatMap(List::stream)\n .forEach(\n part -> {\n part.text().ifPresent(sb::append);\n part.functionCall()\n .ifPresent(functionCall -> sb.append(\"Function Call: \").append(functionCall));\n part.functionResponse()\n .ifPresent(\n functionResponse ->\n sb.append(\"Function Response: \").append(functionResponse));\n });\n return sb.toString();\n }\n\n /** Builder for {@link Event}. */\n public static class Builder {\n\n private String id;\n private String invocationId;\n private String author;\n private Optional content = Optional.empty();\n private EventActions actions;\n private Optional> longRunningToolIds = Optional.empty();\n private Optional partial = Optional.empty();\n private Optional turnComplete = Optional.empty();\n private Optional errorCode = Optional.empty();\n private Optional errorMessage = Optional.empty();\n private Optional interrupted = Optional.empty();\n private Optional branch = Optional.empty();\n private Optional groundingMetadata = Optional.empty();\n private Optional timestamp = Optional.empty();\n\n @JsonCreator\n private static Builder create() {\n return new Builder();\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"id\")\n public Builder id(String value) {\n this.id = value;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"invocationId\")\n public Builder invocationId(String value) {\n this.invocationId = value;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"author\")\n public Builder author(String value) {\n this.author = value;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"content\")\n public Builder content(@Nullable Content value) {\n this.content = Optional.ofNullable(value);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder content(Optional value) {\n this.content = value;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"actions\")\n public Builder actions(EventActions value) {\n this.actions = value;\n return this;\n }\n\n Optional actions() {\n return Optional.ofNullable(actions);\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"longRunningToolIds\")\n public Builder longRunningToolIds(@Nullable Set value) {\n this.longRunningToolIds = Optional.ofNullable(value);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder longRunningToolIds(Optional> value) {\n this.longRunningToolIds = value;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"partial\")\n public Builder partial(@Nullable Boolean value) {\n this.partial = Optional.ofNullable(value);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder partial(Optional value) {\n this.partial = value;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"turnComplete\")\n public Builder turnComplete(@Nullable Boolean value) {\n this.turnComplete = Optional.ofNullable(value);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder turnComplete(Optional value) {\n this.turnComplete = value;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"errorCode\")\n public Builder errorCode(@Nullable FinishReason value) {\n this.errorCode = Optional.ofNullable(value);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder errorCode(Optional value) {\n this.errorCode = value;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"errorMessage\")\n public Builder errorMessage(@Nullable String value) {\n this.errorMessage = Optional.ofNullable(value);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder errorMessage(Optional value) {\n this.errorMessage = value;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"interrupted\")\n public Builder interrupted(@Nullable Boolean value) {\n this.interrupted = Optional.ofNullable(value);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder interrupted(Optional value) {\n this.interrupted = value;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"timestamp\")\n public Builder timestamp(long value) {\n this.timestamp = Optional.of(value);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder timestamp(Optional value) {\n this.timestamp = value;\n return this;\n }\n\n // Getter for builder's timestamp, used in build()\n Optional timestamp() {\n return timestamp;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"branch\")\n public Builder branch(@Nullable String value) {\n this.branch = Optional.ofNullable(value);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder branch(Optional value) {\n this.branch = value;\n return this;\n }\n\n // Getter for builder's branch, used in build()\n Optional branch() {\n return branch;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"groundingMetadata\")\n public Builder groundingMetadata(@Nullable GroundingMetadata value) {\n this.groundingMetadata = Optional.ofNullable(value);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder groundingMetadata(Optional value) {\n this.groundingMetadata = value;\n return this;\n }\n\n Optional groundingMetadata() {\n return groundingMetadata;\n }\n\n public Event build() {\n Event event = new Event();\n event.setId(id);\n event.setInvocationId(invocationId);\n event.setAuthor(author);\n event.setContent(content);\n event.setLongRunningToolIds(longRunningToolIds);\n event.setPartial(partial);\n event.setTurnComplete(turnComplete);\n event.setErrorCode(errorCode);\n event.setErrorMessage(errorMessage);\n event.setInterrupted(interrupted);\n event.branch(branch);\n event.setGroundingMetadata(groundingMetadata);\n\n event.setActions(actions().orElse(EventActions.builder().build()));\n event.setTimestamp(timestamp().orElse(Instant.now().toEpochMilli()));\n return event;\n }\n }\n\n public static Builder builder() {\n return new Builder();\n }\n\n /** Parses an event from a JSON string. */\n public static Event fromJson(String json) {\n return fromJsonString(json, Event.class);\n }\n\n /** Creates a builder pre-filled with this event's values. */\n public Builder toBuilder() {\n Builder builder =\n new Builder()\n .id(this.id)\n .invocationId(this.invocationId)\n .author(this.author)\n .content(this.content)\n .actions(this.actions)\n .longRunningToolIds(this.longRunningToolIds)\n .partial(this.partial)\n .turnComplete(this.turnComplete)\n .errorCode(this.errorCode)\n .errorMessage(this.errorMessage)\n .interrupted(this.interrupted)\n .branch(this.branch)\n .groundingMetadata(this.groundingMetadata);\n if (this.timestamp != 0) {\n builder.timestamp(this.timestamp);\n }\n return builder;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (!(obj instanceof Event other)) {\n return false;\n }\n return timestamp == other.timestamp\n && Objects.equals(id, other.id)\n && Objects.equals(invocationId, other.invocationId)\n && Objects.equals(author, other.author)\n && Objects.equals(content, other.content)\n && Objects.equals(actions, other.actions)\n && Objects.equals(longRunningToolIds, other.longRunningToolIds)\n && Objects.equals(partial, other.partial)\n && Objects.equals(turnComplete, other.turnComplete)\n && Objects.equals(errorCode, other.errorCode)\n && Objects.equals(errorMessage, other.errorMessage)\n && Objects.equals(interrupted, other.interrupted)\n && Objects.equals(branch, other.branch)\n && Objects.equals(groundingMetadata, other.groundingMetadata);\n }\n\n @Override\n public String toString() {\n return toJson();\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(\n id,\n invocationId,\n author,\n content,\n actions,\n longRunningToolIds,\n partial,\n turnComplete,\n errorCode,\n errorMessage,\n interrupted,\n branch,\n groundingMetadata,\n timestamp);\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/models/GeminiLlmConnection.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.models;\n\nimport static com.google.common.collect.ImmutableList.toImmutableList;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.genai.AsyncSession;\nimport com.google.genai.Client;\nimport com.google.genai.types.Blob;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.FinishReason;\nimport com.google.genai.types.FunctionCall;\nimport com.google.genai.types.FunctionResponse;\nimport com.google.genai.types.LiveConnectConfig;\nimport com.google.genai.types.LiveSendClientContentParameters;\nimport com.google.genai.types.LiveSendRealtimeInputParameters;\nimport com.google.genai.types.LiveSendToolResponseParameters;\nimport com.google.genai.types.LiveServerContent;\nimport com.google.genai.types.LiveServerMessage;\nimport com.google.genai.types.LiveServerToolCall;\nimport com.google.genai.types.Part;\nimport io.reactivex.rxjava3.core.Completable;\nimport io.reactivex.rxjava3.core.Flowable;\nimport io.reactivex.rxjava3.processors.PublishProcessor;\nimport java.net.SocketException;\nimport java.util.List;\nimport java.util.Objects;\nimport java.util.Optional;\nimport java.util.concurrent.CompletableFuture;\nimport java.util.concurrent.CompletionException;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * Manages a persistent, bidirectional connection to the Gemini model via WebSockets for real-time\n * interaction.\n *\n *

This connection allows sending conversation history, individual messages, function responses,\n * and real-time media blobs (like audio chunks) while continuously receiving responses from the\n * model.\n */\npublic final class GeminiLlmConnection implements BaseLlmConnection {\n\n private static final Logger logger = LoggerFactory.getLogger(GeminiLlmConnection.class);\n\n private final Client apiClient;\n private final String modelName;\n private final LiveConnectConfig connectConfig;\n private final CompletableFuture sessionFuture;\n private final PublishProcessor responseProcessor = PublishProcessor.create();\n private final Flowable responseFlowable = responseProcessor.serialize();\n private final AtomicBoolean closed = new AtomicBoolean(false);\n\n /**\n * Establishes a new connection.\n *\n * @param apiClient The API client for communication.\n * @param modelName The specific Gemini model endpoint (e.g., \"gemini-2.0-flash).\n * @param connectConfig Configuration parameters for the live session.\n */\n GeminiLlmConnection(Client apiClient, String modelName, LiveConnectConfig connectConfig) {\n this.apiClient = Objects.requireNonNull(apiClient);\n this.modelName = Objects.requireNonNull(modelName);\n this.connectConfig = Objects.requireNonNull(connectConfig);\n\n this.sessionFuture =\n this.apiClient\n .async\n .live\n .connect(this.modelName, this.connectConfig)\n .whenCompleteAsync(\n (session, throwable) -> {\n if (throwable != null) {\n handleConnectionError(throwable);\n } else if (session != null) {\n setupReceiver(session);\n } else if (!closed.get()) {\n handleConnectionError(\n new SocketException(\"WebSocket connection failed without explicit error.\"));\n }\n });\n }\n\n /** Configures the session to forward incoming messages to the response processor. */\n private void setupReceiver(AsyncSession session) {\n if (closed.get()) {\n closeSessionIgnoringErrors(session);\n return;\n }\n session\n .receive(this::handleServerMessage)\n .exceptionally(\n error -> {\n handleReceiveError(error);\n return null;\n });\n }\n\n /** Processes messages received from the WebSocket server. */\n private void handleServerMessage(LiveServerMessage message) {\n if (closed.get()) {\n return;\n }\n\n logger.debug(\"Received server message: {}\", message.toJson());\n\n Optional llmResponse = convertToServerResponse(message);\n llmResponse.ifPresent(responseProcessor::onNext);\n }\n\n /** Converts a server message into the standardized LlmResponse format. */\n private Optional convertToServerResponse(LiveServerMessage message) {\n LlmResponse.Builder builder = LlmResponse.builder();\n\n if (message.serverContent().isPresent()) {\n LiveServerContent serverContent = message.serverContent().get();\n serverContent.modelTurn().ifPresent(builder::content);\n builder\n .partial(serverContent.turnComplete().map(completed -> !completed).orElse(false))\n .turnComplete(serverContent.turnComplete().orElse(false));\n } else if (message.toolCall().isPresent()) {\n LiveServerToolCall toolCall = message.toolCall().get();\n toolCall\n .functionCalls()\n .ifPresent(\n calls -> {\n for (FunctionCall call : calls) {\n builder.content(\n Content.builder()\n .parts(ImmutableList.of(Part.builder().functionCall(call).build()))\n .build());\n }\n });\n builder.partial(false).turnComplete(false);\n } else if (message.usageMetadata().isPresent()) {\n logger.debug(\"Received usage metadata: {}\", message.usageMetadata().get());\n return Optional.empty();\n } else if (message.toolCallCancellation().isPresent()) {\n logger.debug(\"Received tool call cancellation: {}\", message.toolCallCancellation().get());\n // TODO: implement proper CFC and thus tool call cancellation handling.\n return Optional.empty();\n } else if (message.setupComplete().isPresent()) {\n logger.debug(\"Received setup complete.\");\n return Optional.empty();\n } else {\n logger.warn(\"Received unknown or empty server message: {}\", message.toJson());\n builder\n .errorCode(new FinishReason(\"Unknown server message.\"))\n .errorMessage(\"Received unknown server message.\");\n }\n\n return Optional.of(builder.build());\n }\n\n /** Handles errors that occur *during* the initial connection attempt. */\n private void handleConnectionError(Throwable throwable) {\n if (closed.compareAndSet(false, true)) {\n logger.error(\"WebSocket connection failed\", throwable);\n Throwable cause =\n (throwable instanceof CompletionException) ? throwable.getCause() : throwable;\n responseProcessor.onError(cause);\n }\n }\n\n /** Handles errors reported by the WebSocket client *after* connection (e.g., receive errors). */\n private void handleReceiveError(Throwable throwable) {\n if (closed.compareAndSet(false, true)) {\n logger.error(\"Error during WebSocket receive operation\", throwable);\n responseProcessor.onError(throwable);\n sessionFuture.thenAccept(this::closeSessionIgnoringErrors).exceptionally(err -> null);\n }\n }\n\n @Override\n public Completable sendHistory(List history) {\n return sendClientContentInternal(\n LiveSendClientContentParameters.builder().turns(history).build());\n }\n\n @Override\n public Completable sendContent(Content content) {\n Objects.requireNonNull(content, \"content cannot be null\");\n\n Optional> functionResponses = extractFunctionResponses(content);\n\n if (functionResponses.isPresent()) {\n return sendToolResponseInternal(\n LiveSendToolResponseParameters.builder()\n .functionResponses(functionResponses.get())\n .build());\n } else {\n return sendClientContentInternal(\n LiveSendClientContentParameters.builder().turns(ImmutableList.of(content)).build());\n }\n }\n\n /** Extracts FunctionResponse parts from a Content object if all parts are FunctionResponses. */\n private Optional> extractFunctionResponses(Content content) {\n if (content.parts().isEmpty() || content.parts().get().isEmpty()) {\n return Optional.empty();\n }\n\n ImmutableList responses =\n content.parts().get().stream()\n .map(Part::functionResponse)\n .flatMap(Optional::stream)\n .collect(toImmutableList());\n\n // Ensure *all* parts were function responses\n if (responses.size() == content.parts().get().size()) {\n return Optional.of(responses);\n } else {\n return Optional.empty();\n }\n }\n\n @Override\n public Completable sendRealtime(Blob blob) {\n return Completable.fromFuture(\n sessionFuture.thenCompose(\n session ->\n session.sendRealtimeInput(\n LiveSendRealtimeInputParameters.builder().media(blob).build())));\n }\n\n /** Helper to send client content parameters. */\n private Completable sendClientContentInternal(LiveSendClientContentParameters parameters) {\n return Completable.fromFuture(\n sessionFuture.thenCompose(session -> session.sendClientContent(parameters)));\n }\n\n /** Helper to send tool response parameters. */\n private Completable sendToolResponseInternal(LiveSendToolResponseParameters parameters) {\n return Completable.fromFuture(\n sessionFuture.thenCompose(session -> session.sendToolResponse(parameters)));\n }\n\n @Override\n public Flowable receive() {\n return responseFlowable;\n }\n\n @Override\n public void close() {\n closeInternal(null);\n }\n\n @Override\n public void close(Throwable throwable) {\n Objects.requireNonNull(throwable, \"throwable cannot be null for close\");\n closeInternal(throwable);\n }\n\n /** Internal method to handle closing logic and signal completion/error. */\n private void closeInternal(Throwable throwable) {\n if (closed.compareAndSet(false, true)) {\n logger.debug(\"Closing GeminiConnection.\", throwable);\n\n if (throwable == null) {\n responseProcessor.onComplete();\n } else {\n responseProcessor.onError(throwable);\n }\n\n if (sessionFuture.isDone()) {\n sessionFuture.thenAccept(this::closeSessionIgnoringErrors).exceptionally(err -> null);\n } else {\n sessionFuture.cancel(false);\n }\n }\n }\n\n /** Closes the AsyncSession safely, logging any errors. */\n private void closeSessionIgnoringErrors(AsyncSession session) {\n if (session != null) {\n session\n .close()\n .exceptionally(\n closeError -> {\n logger.warn(\"Error occurred while closing AsyncSession\", closeError);\n return null; // Suppress error during close\n });\n }\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/llmflows/BaseLlmFlow.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows.llmflows;\n\nimport com.google.adk.Telemetry;\nimport com.google.adk.agents.BaseAgent;\nimport com.google.adk.agents.CallbackContext;\nimport com.google.adk.agents.Callbacks.AfterModelCallback;\nimport com.google.adk.agents.Callbacks.BeforeModelCallback;\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.agents.LiveRequest;\nimport com.google.adk.agents.LlmAgent;\nimport com.google.adk.agents.ReadonlyContext;\nimport com.google.adk.agents.RunConfig.StreamingMode;\nimport com.google.adk.events.Event;\nimport com.google.adk.exceptions.LlmCallsLimitExceededException;\nimport com.google.adk.flows.BaseFlow;\nimport com.google.adk.flows.llmflows.RequestProcessor.RequestProcessingResult;\nimport com.google.adk.flows.llmflows.ResponseProcessor.ResponseProcessingResult;\nimport com.google.adk.models.BaseLlm;\nimport com.google.adk.models.BaseLlmConnection;\nimport com.google.adk.models.LlmRegistry;\nimport com.google.adk.models.LlmRequest;\nimport com.google.adk.models.LlmResponse;\nimport com.google.adk.tools.ToolContext;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Iterables;\nimport com.google.genai.types.FunctionResponse;\nimport io.opentelemetry.api.trace.Span;\nimport io.opentelemetry.api.trace.StatusCode;\nimport io.opentelemetry.context.Scope;\nimport io.reactivex.rxjava3.core.Completable;\nimport io.reactivex.rxjava3.core.Flowable;\nimport io.reactivex.rxjava3.core.Maybe;\nimport io.reactivex.rxjava3.core.Single;\nimport io.reactivex.rxjava3.disposables.Disposable;\nimport io.reactivex.rxjava3.observers.DisposableCompletableObserver;\nimport io.reactivex.rxjava3.schedulers.Schedulers;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.Set;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/** A basic flow that calls the LLM in a loop until a final response is generated. */\npublic abstract class BaseLlmFlow implements BaseFlow {\n private static final Logger logger = LoggerFactory.getLogger(BaseLlmFlow.class);\n\n protected final List requestProcessors;\n protected final List responseProcessors;\n\n // Warning: This is local, in-process state that won't be preserved if the runtime is restarted.\n // \"Max steps\" is experimental and may evolve in the future (e.g., to support persistence).\n protected int stepsCompleted = 0;\n protected final int maxSteps;\n\n public BaseLlmFlow(\n List requestProcessors, List responseProcessors) {\n this(requestProcessors, responseProcessors, /* maxSteps= */ Optional.empty());\n }\n\n public BaseLlmFlow(\n List requestProcessors,\n List responseProcessors,\n Optional maxSteps) {\n this.requestProcessors = requestProcessors;\n this.responseProcessors = responseProcessors;\n this.maxSteps = maxSteps.orElse(Integer.MAX_VALUE);\n }\n\n /**\n * Pre-processes the LLM request before sending it to the LLM. Executes all registered {@link\n * RequestProcessor}.\n */\n protected Single preprocess(\n InvocationContext context, LlmRequest llmRequest) {\n\n List> eventIterables = new ArrayList<>();\n LlmAgent agent = (LlmAgent) context.agent();\n\n Single currentLlmRequest = Single.just(llmRequest);\n for (RequestProcessor processor : requestProcessors) {\n currentLlmRequest =\n currentLlmRequest\n .flatMap(request -> processor.processRequest(context, request))\n .doOnSuccess(\n result -> {\n if (result.events() != null) {\n eventIterables.add(result.events());\n }\n })\n .map(RequestProcessingResult::updatedRequest);\n }\n\n return currentLlmRequest.flatMap(\n processedRequest -> {\n LlmRequest.Builder updatedRequestBuilder = processedRequest.toBuilder();\n\n return agent\n .canonicalTools(new ReadonlyContext(context))\n .concatMapCompletable(\n tool ->\n tool.processLlmRequest(\n updatedRequestBuilder, ToolContext.builder(context).build()))\n .andThen(\n Single.fromCallable(\n () -> {\n Iterable combinedEvents = Iterables.concat(eventIterables);\n return RequestProcessingResult.create(\n updatedRequestBuilder.build(), combinedEvents);\n }));\n });\n }\n\n /**\n * Post-processes the LLM response after receiving it from the LLM. Executes all registered {@link\n * ResponseProcessor} instances. Handles function calls if present in the response.\n */\n protected Single postprocess(\n InvocationContext context,\n Event baseEventForLlmResponse,\n LlmRequest llmRequest,\n LlmResponse llmResponse) {\n\n List> eventIterables = new ArrayList<>();\n Single currentLlmResponse = Single.just(llmResponse);\n for (ResponseProcessor processor : responseProcessors) {\n currentLlmResponse =\n currentLlmResponse\n .flatMap(response -> processor.processResponse(context, response))\n .doOnSuccess(\n result -> {\n if (result.events() != null) {\n eventIterables.add(result.events());\n }\n })\n .map(ResponseProcessingResult::updatedResponse);\n }\n\n return currentLlmResponse.flatMap(\n updatedResponse -> {\n if (updatedResponse.content().isEmpty()\n && updatedResponse.errorCode().isEmpty()\n && !updatedResponse.interrupted().orElse(false)\n && !updatedResponse.turnComplete().orElse(false)) {\n return Single.just(\n ResponseProcessingResult.create(\n updatedResponse, Iterables.concat(eventIterables), Optional.empty()));\n }\n\n Event modelResponseEvent =\n buildModelResponseEvent(baseEventForLlmResponse, llmRequest, updatedResponse);\n eventIterables.add(Collections.singleton(modelResponseEvent));\n\n Maybe maybeFunctionCallEvent =\n modelResponseEvent.functionCalls().isEmpty()\n ? Maybe.empty()\n : Functions.handleFunctionCalls(context, modelResponseEvent, llmRequest.tools());\n\n return maybeFunctionCallEvent\n .map(Optional::of)\n .defaultIfEmpty(Optional.empty())\n .map(\n functionCallEventOpt -> {\n Optional transferToAgent = Optional.empty();\n if (functionCallEventOpt.isPresent()) {\n Event functionCallEvent = functionCallEventOpt.get();\n eventIterables.add(Collections.singleton(functionCallEvent));\n transferToAgent = functionCallEvent.actions().transferToAgent();\n }\n Iterable combinedEvents = Iterables.concat(eventIterables);\n return ResponseProcessingResult.create(\n updatedResponse, combinedEvents, transferToAgent);\n });\n });\n }\n\n /**\n * Sends a request to the LLM and returns its response.\n *\n * @param context The invocation context.\n * @param llmRequest The LLM request.\n * @param eventForCallbackUsage An Event object primarily for providing context (like actions) to\n * callbacks. Callbacks should not rely on its ID if they create their own separate events.\n */\n private Flowable callLlm(\n InvocationContext context, LlmRequest llmRequest, Event eventForCallbackUsage) {\n LlmAgent agent = (LlmAgent) context.agent();\n\n return handleBeforeModelCallback(context, llmRequest, eventForCallbackUsage)\n .flatMapPublisher(\n beforeResponse -> {\n if (beforeResponse.isPresent()) {\n return Flowable.just(beforeResponse.get());\n }\n BaseLlm llm =\n agent.resolvedModel().model().isPresent()\n ? agent.resolvedModel().model().get()\n : LlmRegistry.getLlm(agent.resolvedModel().modelName().get());\n return Flowable.defer(\n () -> {\n Span llmCallSpan =\n Telemetry.getTracer().spanBuilder(\"call_llm\").startSpan();\n\n try (Scope scope = llmCallSpan.makeCurrent()) {\n return llm.generateContent(\n llmRequest,\n context.runConfig().streamingMode() == StreamingMode.SSE)\n .doOnNext(\n llmResp -> {\n try (Scope innerScope = llmCallSpan.makeCurrent()) {\n Telemetry.traceCallLlm(\n context, eventForCallbackUsage.id(), llmRequest, llmResp);\n }\n })\n .doOnError(\n error -> {\n llmCallSpan.setStatus(StatusCode.ERROR, error.getMessage());\n llmCallSpan.recordException(error);\n })\n .doFinally(llmCallSpan::end);\n }\n })\n .concatMap(\n llmResp ->\n handleAfterModelCallback(context, llmResp, eventForCallbackUsage)\n .toFlowable());\n });\n }\n\n /**\n * Invokes {@link BeforeModelCallback}s. If any returns a response, it's used instead of calling\n * the LLM.\n *\n * @return A {@link Single} with the callback result or {@link Optional#empty()}.\n */\n private Single> handleBeforeModelCallback(\n InvocationContext context, LlmRequest llmRequest, Event modelResponseEvent) {\n LlmAgent agent = (LlmAgent) context.agent();\n\n Optional> callbacksOpt = agent.beforeModelCallback();\n if (callbacksOpt.isEmpty() || callbacksOpt.get().isEmpty()) {\n return Single.just(Optional.empty());\n }\n\n Event callbackEvent = modelResponseEvent.toBuilder().build();\n List callbacks = callbacksOpt.get();\n\n return Flowable.fromIterable(callbacks)\n .concatMapSingle(\n callback -> {\n CallbackContext callbackContext =\n new CallbackContext(context, callbackEvent.actions());\n return callback\n .call(callbackContext, llmRequest)\n .map(Optional::of)\n .defaultIfEmpty(Optional.empty());\n })\n .filter(Optional::isPresent)\n .firstElement()\n .switchIfEmpty(Single.just(Optional.empty()));\n }\n\n /**\n * Invokes {@link AfterModelCallback}s after an LLM response. If any returns a response, it\n * replaces the original.\n *\n * @return A {@link Single} with the final {@link LlmResponse}.\n */\n private Single handleAfterModelCallback(\n InvocationContext context, LlmResponse llmResponse, Event modelResponseEvent) {\n LlmAgent agent = (LlmAgent) context.agent();\n Optional> callbacksOpt = agent.afterModelCallback();\n\n if (callbacksOpt.isEmpty() || callbacksOpt.get().isEmpty()) {\n return Single.just(llmResponse);\n }\n\n Event callbackEvent = modelResponseEvent.toBuilder().content(llmResponse.content()).build();\n List callbacks = callbacksOpt.get();\n\n return Flowable.fromIterable(callbacks)\n .concatMapSingle(\n callback -> {\n CallbackContext callbackContext =\n new CallbackContext(context, callbackEvent.actions());\n return callback\n .call(callbackContext, llmResponse)\n .map(Optional::of)\n .defaultIfEmpty(Optional.empty());\n })\n .filter(Optional::isPresent)\n .firstElement()\n .map(Optional::get)\n .switchIfEmpty(Single.just(llmResponse));\n }\n\n /**\n * Executes a single iteration of the LLM flow: preprocessing → LLM call → postprocessing.\n *\n *

Handles early termination, LLM call limits, and agent transfer if needed.\n *\n * @return A {@link Flowable} of {@link Event} objects from this step.\n * @throws LlmCallsLimitExceededException if the agent exceeds allowed LLM invocations.\n * @throws IllegalStateException if a transfer agent is specified but not found.\n */\n private Flowable runOneStep(InvocationContext context) {\n LlmRequest initialLlmRequest = LlmRequest.builder().build();\n\n return preprocess(context, initialLlmRequest)\n .flatMapPublisher(\n preResult -> {\n LlmRequest llmRequestAfterPreprocess = preResult.updatedRequest();\n Iterable preEvents = preResult.events();\n\n if (context.endInvocation()) {\n logger.debug(\"End invocation requested during preprocessing.\");\n return Flowable.fromIterable(preEvents);\n }\n\n try {\n context.incrementLlmCallsCount();\n } catch (LlmCallsLimitExceededException e) {\n logger.error(\"LLM calls limit exceeded.\", e);\n return Flowable.fromIterable(preEvents).concatWith(Flowable.error(e));\n }\n\n final Event mutableEventTemplate =\n Event.builder()\n .id(Event.generateEventId())\n .invocationId(context.invocationId())\n .author(context.agent().name())\n .branch(context.branch())\n .build();\n\n Flowable restOfFlow =\n callLlm(context, llmRequestAfterPreprocess, mutableEventTemplate)\n .concatMap(\n llmResponse -> {\n Single postResultSingle =\n postprocess(\n context,\n mutableEventTemplate,\n llmRequestAfterPreprocess,\n llmResponse);\n\n return postResultSingle\n .doOnSuccess(\n ignored -> {\n String oldId = mutableEventTemplate.id();\n mutableEventTemplate.setId(Event.generateEventId());\n logger.debug(\n \"Updated mutableEventTemplate ID from {} to {} for next\"\n + \" LlmResponse\",\n oldId,\n mutableEventTemplate.id());\n })\n .toFlowable();\n })\n .concatMap(\n postResult -> {\n Flowable postProcessedEvents =\n Flowable.fromIterable(postResult.events());\n if (postResult.transferToAgent().isPresent()) {\n String agentToTransfer = postResult.transferToAgent().get();\n logger.debug(\"Transferring to agent: {}\", agentToTransfer);\n BaseAgent rootAgent = context.agent().rootAgent();\n BaseAgent nextAgent = rootAgent.findAgent(agentToTransfer);\n if (nextAgent == null) {\n String errorMsg =\n \"Agent not found for transfer: \" + agentToTransfer;\n logger.error(errorMsg);\n return postProcessedEvents.concatWith(\n Flowable.error(new IllegalStateException(errorMsg)));\n }\n return postProcessedEvents.concatWith(\n Flowable.defer(() -> nextAgent.runAsync(context)));\n }\n return postProcessedEvents;\n });\n\n return restOfFlow.startWithIterable(preEvents);\n });\n }\n\n /**\n * Executes the full LLM flow by repeatedly calling {@link #runOneStep} until a final response is\n * produced.\n *\n * @return A {@link Flowable} of all {@link Event}s generated during the flow.\n */\n @Override\n public Flowable run(InvocationContext invocationContext) {\n Flowable currentStepEvents = runOneStep(invocationContext).cache();\n if (++stepsCompleted >= maxSteps) {\n logger.debug(\"Ending flow execution because max steps reached.\");\n return currentStepEvents;\n }\n\n return currentStepEvents.concatWith(\n currentStepEvents\n .toList()\n .flatMapPublisher(\n eventList -> {\n if (eventList.isEmpty()\n || Iterables.getLast(eventList).finalResponse()\n || Iterables.getLast(eventList).actions().endInvocation().orElse(false)) {\n logger.debug(\n \"Ending flow execution based on final response, endInvocation action or\"\n + \" empty event list.\");\n return Flowable.empty();\n } else {\n logger.debug(\"Continuing to next step of the flow.\");\n return Flowable.defer(() -> run(invocationContext));\n }\n }));\n }\n\n /**\n * Executes the LLM flow in streaming mode.\n *\n *

Handles sending history and live requests to the LLM, receiving responses, processing them,\n * and managing agent transfers.\n *\n * @return A {@link Flowable} of {@link Event}s streamed in real-time.\n */\n @Override\n public Flowable runLive(InvocationContext invocationContext) {\n LlmRequest llmRequest = LlmRequest.builder().build();\n\n return preprocess(invocationContext, llmRequest)\n .flatMapPublisher(\n preResult -> {\n LlmRequest llmRequestAfterPreprocess = preResult.updatedRequest();\n if (invocationContext.endInvocation()) {\n return Flowable.fromIterable(preResult.events());\n }\n\n String eventIdForSendData = Event.generateEventId();\n LlmAgent agent = (LlmAgent) invocationContext.agent();\n BaseLlm llm =\n agent.resolvedModel().model().isPresent()\n ? agent.resolvedModel().model().get()\n : LlmRegistry.getLlm(agent.resolvedModel().modelName().get());\n BaseLlmConnection connection = llm.connect(llmRequestAfterPreprocess);\n Completable historySent =\n llmRequestAfterPreprocess.contents().isEmpty()\n ? Completable.complete()\n : Completable.defer(\n () -> {\n Span sendDataSpan =\n Telemetry.getTracer().spanBuilder(\"send_data\").startSpan();\n try (Scope scope = sendDataSpan.makeCurrent()) {\n return connection\n .sendHistory(llmRequestAfterPreprocess.contents())\n .doOnComplete(\n () -> {\n try (Scope innerScope = sendDataSpan.makeCurrent()) {\n Telemetry.traceSendData(\n invocationContext,\n eventIdForSendData,\n llmRequestAfterPreprocess.contents());\n }\n })\n .doOnError(\n error -> {\n sendDataSpan.setStatus(\n StatusCode.ERROR, error.getMessage());\n sendDataSpan.recordException(error);\n try (Scope innerScope = sendDataSpan.makeCurrent()) {\n Telemetry.traceSendData(\n invocationContext,\n eventIdForSendData,\n llmRequestAfterPreprocess.contents());\n }\n })\n .doFinally(sendDataSpan::end);\n }\n });\n\n Flowable liveRequests = invocationContext.liveRequestQueue().get().get();\n Disposable sendTask =\n historySent\n .observeOn(agent.executor().map(Schedulers::from).orElse(Schedulers.io()))\n .andThen(\n liveRequests\n .onBackpressureBuffer()\n .concatMapCompletable(\n request -> {\n if (request.content().isPresent()) {\n return connection.sendContent(request.content().get());\n } else if (request.blob().isPresent()) {\n return connection.sendRealtime(request.blob().get());\n }\n return Completable.fromAction(connection::close);\n }))\n .subscribeWith(\n new DisposableCompletableObserver() {\n @Override\n public void onComplete() {\n connection.close();\n }\n\n @Override\n public void onError(Throwable e) {\n connection.close(e);\n }\n });\n\n Event.Builder liveEventBuilderTemplate =\n Event.builder()\n .invocationId(invocationContext.invocationId())\n .author(invocationContext.agent().name())\n .branch(invocationContext.branch());\n\n Flowable receiveFlow =\n connection\n .receive()\n .flatMapSingle(\n llmResponse -> {\n Event baseEventForThisLlmResponse =\n liveEventBuilderTemplate.id(Event.generateEventId()).build();\n return postprocess(\n invocationContext,\n baseEventForThisLlmResponse,\n llmRequestAfterPreprocess,\n llmResponse);\n })\n .flatMap(\n postResult -> {\n Flowable events = Flowable.fromIterable(postResult.events());\n if (postResult.transferToAgent().isPresent()) {\n BaseAgent rootAgent = invocationContext.agent().rootAgent();\n BaseAgent nextAgent =\n rootAgent.findAgent(postResult.transferToAgent().get());\n if (nextAgent == null) {\n throw new IllegalStateException(\n \"Agent not found: \" + postResult.transferToAgent().get());\n }\n Flowable nextAgentEvents =\n nextAgent.runLive(invocationContext);\n events = Flowable.concat(events, nextAgentEvents);\n }\n return events;\n })\n .doOnNext(\n event -> {\n ImmutableList functionResponses =\n event.functionResponses();\n if (!functionResponses.isEmpty()) {\n invocationContext\n .liveRequestQueue()\n .get()\n .content(event.content().get());\n }\n if (functionResponses.stream()\n .anyMatch(\n functionResponse ->\n functionResponse\n .name()\n .orElse(\"\")\n .equals(\"transferToAgent\"))\n || event.actions().endInvocation().orElse(false)) {\n sendTask.dispose();\n connection.close();\n }\n });\n\n return receiveFlow\n .takeWhile(event -> !event.actions().endInvocation().orElse(false))\n .startWithIterable(preResult.events());\n });\n }\n\n /**\n * Builds an {@link Event} from LLM response, request, and base event data.\n *\n *

Populates the event with LLM output and tool function call metadata.\n *\n * @return A fully constructed {@link Event} representing the LLM response.\n */\n private Event buildModelResponseEvent(\n Event baseEventForLlmResponse, LlmRequest llmRequest, LlmResponse llmResponse) {\n Event.Builder eventBuilder =\n baseEventForLlmResponse.toBuilder()\n .content(llmResponse.content())\n .partial(llmResponse.partial())\n .errorCode(llmResponse.errorCode())\n .errorMessage(llmResponse.errorMessage())\n .interrupted(llmResponse.interrupted())\n .turnComplete(llmResponse.turnComplete())\n .groundingMetadata(llmResponse.groundingMetadata());\n\n Event event = eventBuilder.build();\n\n if (!event.functionCalls().isEmpty()) {\n Functions.populateClientFunctionCallId(event);\n Set longRunningToolIds =\n Functions.getLongRunningFunctionCalls(event.functionCalls(), llmRequest.tools());\n if (!longRunningToolIds.isEmpty()) {\n event.setLongRunningToolIds(Optional.of(longRunningToolIds));\n }\n }\n return event;\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/mcp/ConversionUtils.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools.mcp;\n\nimport com.google.adk.tools.BaseTool;\nimport com.google.genai.types.FunctionDeclaration;\nimport com.google.genai.types.Schema;\nimport io.modelcontextprotocol.spec.McpSchema;\nimport java.util.Optional;\n\n/** Utility class for converting between different representations of MCP tools. */\npublic final class ConversionUtils {\n\n public McpSchema.Tool adkToMcpToolType(BaseTool tool) {\n Optional toolDeclaration = tool.declaration();\n if (toolDeclaration.isEmpty()) {\n return new McpSchema.Tool(tool.name(), tool.description(), \"\");\n }\n Schema geminiSchema = toolDeclaration.get().parameters().get();\n return new McpSchema.Tool(tool.name(), tool.description(), geminiSchema.toJson());\n }\n\n private ConversionUtils() {}\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/llmflows/AgentTransfer.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows.llmflows;\n\nimport com.google.adk.agents.BaseAgent;\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.agents.LlmAgent;\nimport com.google.adk.events.EventActions;\nimport com.google.adk.models.LlmRequest;\nimport com.google.adk.tools.FunctionTool;\nimport com.google.adk.tools.ToolContext;\nimport com.google.common.collect.ImmutableList;\nimport io.reactivex.rxjava3.core.Single;\nimport java.lang.reflect.Method;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/** {@link RequestProcessor} that handles agent transfer for LLM flow. */\npublic final class AgentTransfer implements RequestProcessor {\n\n public AgentTransfer() {}\n\n @Override\n public Single processRequest(\n InvocationContext context, LlmRequest request) {\n BaseAgent baseAgent = context.agent();\n if (!(baseAgent instanceof LlmAgent agent)) {\n throw new IllegalArgumentException(\n \"Base agent in InvocationContext is not an instance of Agent.\");\n }\n\n List transferTargets = getTransferTargets(agent);\n if (transferTargets.isEmpty()) {\n return Single.just(\n RequestProcessor.RequestProcessingResult.create(request, ImmutableList.of()));\n }\n\n LlmRequest.Builder builder =\n request.toBuilder()\n .appendInstructions(\n ImmutableList.of(buildTargetAgentsInstructions(agent, transferTargets)));\n Method transferToAgentMethod;\n try {\n transferToAgentMethod =\n AgentTransfer.class.getMethod(\"transferToAgent\", String.class, ToolContext.class);\n } catch (NoSuchMethodException e) {\n throw new IllegalStateException(e);\n }\n FunctionTool agentTransferTool = FunctionTool.create(transferToAgentMethod);\n agentTransferTool.processLlmRequest(builder, ToolContext.builder(context).build());\n return Single.just(\n RequestProcessor.RequestProcessingResult.create(builder.build(), ImmutableList.of()));\n }\n\n /** Builds a string with the target agent’s name and description. */\n private String buildTargetAgentsInfo(BaseAgent targetAgent) {\n return String.format(\n \"Agent name: %s\\nAgent description: %s\", targetAgent.name(), targetAgent.description());\n }\n\n /** Builds LLM instructions about when and how to transfer to another agent. */\n private String buildTargetAgentsInstructions(LlmAgent agent, List transferTargets) {\n StringBuilder sb = new StringBuilder();\n sb.append(\"You have a list of other agents to transfer to:\\n\");\n for (BaseAgent targetAgent : transferTargets) {\n sb.append(buildTargetAgentsInfo(targetAgent));\n sb.append(\"\\n\");\n }\n sb.append(\n \"If you are the best to answer the question according to your description, you can answer\"\n + \" it.\\n\");\n sb.append(\n \"If another agent is better for answering the question according to its description, call\"\n + \" `transferToAgent` function to transfer the question to that agent. When\"\n + \" transferring, do not generate any text other than the function call.\\n\");\n if (agent.parentAgent() != null) {\n sb.append(\"Your parent agent is \");\n sb.append(agent.parentAgent().name());\n sb.append(\n \".If neither the other agents nor you are best for answering the question according to\"\n + \" the descriptions, transfer to your parent agent. If you don't have parent agent,\"\n + \" try answer by yourself.\\n\");\n }\n return sb.toString();\n }\n\n /** Returns valid transfer targets: sub-agents, parent, and peers (if allowed). */\n private List getTransferTargets(LlmAgent agent) {\n List transferTargets = new ArrayList<>();\n transferTargets.addAll(agent.subAgents()); // Add all sub-agents\n\n BaseAgent parent = agent.parentAgent();\n // Agents eligible to transfer must have an LLM-based agent parent.\n if (!(parent instanceof LlmAgent)) {\n return transferTargets;\n }\n\n if (!agent.disallowTransferToParent()) {\n transferTargets.add(parent);\n }\n\n if (!agent.disallowTransferToPeers()) {\n for (BaseAgent peerAgent : parent.subAgents()) {\n if (!peerAgent.name().equals(agent.name())) {\n transferTargets.add(peerAgent);\n }\n }\n }\n\n return transferTargets;\n }\n\n /** Marks the target agent for transfer using the tool context. */\n public static void transferToAgent(String agentName, ToolContext toolContext) {\n EventActions eventActions = toolContext.eventActions();\n toolContext.setActions(eventActions.toBuilder().transferToAgent(agentName).build());\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/BuiltInCodeExecutionTool.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools;\n\nimport com.google.adk.models.LlmRequest;\nimport com.google.common.collect.ImmutableList;\nimport com.google.genai.types.GenerateContentConfig;\nimport com.google.genai.types.Tool;\nimport com.google.genai.types.ToolCodeExecution;\nimport io.reactivex.rxjava3.core.Completable;\nimport java.util.List;\n\n/**\n * A built-in code execution tool that is automatically invoked by Gemini 2 models.\n *\n *

This tool operates internally within the model and does not require or perform local code\n * execution.\n */\npublic final class BuiltInCodeExecutionTool extends BaseTool {\n\n public BuiltInCodeExecutionTool() {\n super(\"code_execution\", \"code_execution\");\n }\n\n @Override\n public Completable processLlmRequest(\n LlmRequest.Builder llmRequestBuilder, ToolContext toolContext) {\n\n String model = llmRequestBuilder.build().model().get();\n if (model.isEmpty() || !model.startsWith(\"gemini-2\")) {\n return Completable.error(\n new IllegalArgumentException(\"Code execution tool is not supported for model \" + model));\n }\n GenerateContentConfig.Builder configBuilder =\n llmRequestBuilder\n .build()\n .config()\n .map(GenerateContentConfig::toBuilder)\n .orElse(GenerateContentConfig.builder());\n\n List existingTools = configBuilder.build().tools().orElse(ImmutableList.of());\n ImmutableList.Builder updatedToolsBuilder = ImmutableList.builder();\n updatedToolsBuilder\n .addAll(existingTools)\n .add(Tool.builder().codeExecution(ToolCodeExecution.builder().build()).build());\n configBuilder.tools(updatedToolsBuilder.build());\n llmRequestBuilder.config(configBuilder.build());\n return Completable.complete();\n }\n}\n"], ["/adk-java/dev/src/main/java/com/google/adk/web/AdkWebServer.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.web;\n\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.google.adk.JsonBaseModel;\nimport com.google.adk.agents.BaseAgent;\nimport com.google.adk.agents.LiveRequest;\nimport com.google.adk.agents.LiveRequestQueue;\nimport com.google.adk.agents.RunConfig;\nimport com.google.adk.agents.RunConfig.StreamingMode;\nimport com.google.adk.artifacts.BaseArtifactService;\nimport com.google.adk.artifacts.InMemoryArtifactService;\nimport com.google.adk.artifacts.ListArtifactsResponse;\nimport com.google.adk.events.Event;\nimport com.google.adk.runner.Runner;\nimport com.google.adk.sessions.BaseSessionService;\nimport com.google.adk.sessions.InMemorySessionService;\nimport com.google.adk.sessions.ListSessionsResponse;\nimport com.google.adk.sessions.Session;\nimport com.google.adk.web.config.AgentLoadingProperties;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Lists;\nimport com.google.genai.types.Blob;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.FunctionCall;\nimport com.google.genai.types.FunctionResponse;\nimport com.google.genai.types.Modality;\nimport com.google.genai.types.Part;\nimport io.opentelemetry.api.OpenTelemetry;\nimport io.opentelemetry.api.common.AttributeKey;\nimport io.opentelemetry.api.common.Attributes;\nimport io.opentelemetry.api.trace.SpanId;\nimport io.opentelemetry.sdk.OpenTelemetrySdk;\nimport io.opentelemetry.sdk.common.CompletableResultCode;\nimport io.opentelemetry.sdk.resources.Resource;\nimport io.opentelemetry.sdk.trace.SdkTracerProvider;\nimport io.opentelemetry.sdk.trace.data.SpanData;\nimport io.opentelemetry.sdk.trace.export.SimpleSpanProcessor;\nimport io.opentelemetry.sdk.trace.export.SpanExporter;\nimport io.reactivex.rxjava3.core.Flowable;\nimport io.reactivex.rxjava3.core.Maybe;\nimport io.reactivex.rxjava3.core.Single;\nimport io.reactivex.rxjava3.disposables.Disposable;\nimport io.reactivex.rxjava3.schedulers.Schedulers;\nimport java.io.IOException;\nimport java.net.URI;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.Optional;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.stream.Collectors;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.beans.factory.annotation.Qualifier;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.boot.context.properties.ConfigurationPropertiesScan;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.ComponentScan;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.http.MediaType;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.stereotype.Component;\nimport org.springframework.util.MultiValueMap;\nimport org.springframework.web.bind.annotation.DeleteMapping;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.PostMapping;\nimport org.springframework.web.bind.annotation.RequestBody;\nimport org.springframework.web.bind.annotation.RequestParam;\nimport org.springframework.web.bind.annotation.RestController;\nimport org.springframework.web.server.ResponseStatusException;\nimport org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;\nimport org.springframework.web.servlet.config.annotation.ViewControllerRegistry;\nimport org.springframework.web.servlet.config.annotation.WebMvcConfigurer;\nimport org.springframework.web.servlet.mvc.method.annotation.SseEmitter;\nimport org.springframework.web.socket.CloseStatus;\nimport org.springframework.web.socket.TextMessage;\nimport org.springframework.web.socket.WebSocketSession;\nimport org.springframework.web.socket.config.annotation.EnableWebSocket;\nimport org.springframework.web.socket.config.annotation.WebSocketConfigurer;\nimport org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;\nimport org.springframework.web.socket.handler.TextWebSocketHandler;\nimport org.springframework.web.util.UriComponentsBuilder;\n\n/**\n * Single-file Spring Boot application for the Agent Server. Combines configuration, DTOs, and\n * controller logic.\n */\n@SpringBootApplication\n@ConfigurationPropertiesScan\n@ComponentScan(basePackages = {\"com.google.adk.web\", \"com.google.adk.web.config\"})\npublic class AdkWebServer implements WebMvcConfigurer {\n\n private static final Logger log = LoggerFactory.getLogger(AdkWebServer.class);\n\n @Value(\"${adk.web.ui.dir:#{null}}\")\n private String webUiDir;\n\n @Bean\n public BaseSessionService sessionService() {\n // TODO: Add logic to select service based on config (e.g., DB URL)\n log.info(\"Using InMemorySessionService\");\n return new InMemorySessionService();\n }\n\n /**\n * Provides the singleton instance of the ArtifactService (InMemory). TODO: configure this based\n * on config (e.g., DB URL)\n *\n * @return An instance of BaseArtifactService (currently InMemoryArtifactService).\n */\n @Bean\n public BaseArtifactService artifactService() {\n log.info(\"Using InMemoryArtifactService\");\n return new InMemoryArtifactService();\n }\n\n @Bean(\"loadedAgentRegistry\")\n public Map loadedAgentRegistry(\n AgentCompilerLoader loader, AgentLoadingProperties props) {\n if (props.getSourceDir() == null || props.getSourceDir().isEmpty()) {\n log.info(\"adk.agents.source-dir not set. Initializing with an empty agent registry.\");\n return Collections.emptyMap();\n }\n try {\n Map agents = loader.loadAgents();\n log.info(\"Loaded {} dynamic agent(s): {}\", agents.size(), agents.keySet());\n return agents;\n } catch (IOException e) {\n log.error(\"Failed to load dynamic agents\", e);\n return Collections.emptyMap();\n }\n }\n\n @Bean\n public ObjectMapper objectMapper() {\n return JsonBaseModel.getMapper();\n }\n\n /** Service for creating and caching Runner instances. */\n @Component\n public static class RunnerService {\n private static final Logger log = LoggerFactory.getLogger(RunnerService.class);\n\n private final Map agentRegistry;\n private final BaseArtifactService artifactService;\n private final BaseSessionService sessionService;\n private final Map runnerCache = new ConcurrentHashMap<>();\n\n @Autowired\n public RunnerService(\n @Qualifier(\"loadedAgentRegistry\") Map agentRegistry,\n BaseArtifactService artifactService,\n BaseSessionService sessionService) {\n this.agentRegistry = agentRegistry;\n this.artifactService = artifactService;\n this.sessionService = sessionService;\n }\n\n /**\n * Gets the Runner instance for a given application name. Handles potential agent engine ID\n * overrides.\n *\n * @param appName The application name requested by the user.\n * @return A configured Runner instance.\n */\n public Runner getRunner(String appName) {\n return runnerCache.computeIfAbsent(\n appName,\n key -> {\n BaseAgent agent = agentRegistry.get(key);\n if (agent == null) {\n log.error(\n \"Agent/App named '{}' not found in registry. Available apps: {}\",\n key,\n agentRegistry.keySet());\n throw new ResponseStatusException(\n HttpStatus.NOT_FOUND, \"Agent/App not found: \" + key);\n }\n log.info(\n \"RunnerService: Creating Runner for appName: {}, using agent\" + \" definition: {}\",\n appName,\n agent.name());\n return new Runner(agent, appName, this.artifactService, this.sessionService);\n });\n }\n }\n\n /** Configuration class for OpenTelemetry, setting up the tracer provider and span exporter. */\n @Configuration\n public static class OpenTelemetryConfig {\n private static final Logger otelLog = LoggerFactory.getLogger(OpenTelemetryConfig.class);\n\n @Bean\n public ApiServerSpanExporter apiServerSpanExporter() {\n return new ApiServerSpanExporter();\n }\n\n @Bean(destroyMethod = \"shutdown\")\n public SdkTracerProvider sdkTracerProvider(ApiServerSpanExporter apiServerSpanExporter) {\n otelLog.debug(\"Configuring SdkTracerProvider with ApiServerSpanExporter.\");\n Resource resource =\n Resource.getDefault()\n .merge(\n Resource.create(\n Attributes.of(AttributeKey.stringKey(\"service.name\"), \"adk-web-server\")));\n\n return SdkTracerProvider.builder()\n .addSpanProcessor(SimpleSpanProcessor.create(apiServerSpanExporter))\n .setResource(resource)\n .build();\n }\n\n @Bean\n public OpenTelemetry openTelemetrySdk(SdkTracerProvider sdkTracerProvider) {\n otelLog.debug(\"Configuring OpenTelemetrySdk and registering globally.\");\n OpenTelemetrySdk otelSdk =\n OpenTelemetrySdk.builder().setTracerProvider(sdkTracerProvider).buildAndRegisterGlobal();\n\n Runtime.getRuntime().addShutdownHook(new Thread(otelSdk::close));\n return otelSdk;\n }\n }\n\n /**\n * A custom SpanExporter that stores relevant span data. It handles two types of trace data\n * storage: 1. Event-ID based: Stores attributes of specific spans (call_llm, send_data,\n * tool_response) keyed by `gcp.vertex.agent.event_id`. This is used for debugging individual\n * events. 2. Session-ID based: Stores all exported spans and maintains a mapping from\n * `session_id` (extracted from `call_llm` spans) to a list of `trace_id`s. This is used for\n * retrieving all spans related to a session.\n */\n public static class ApiServerSpanExporter implements SpanExporter {\n private static final Logger exporterLog = LoggerFactory.getLogger(ApiServerSpanExporter.class);\n\n private final Map> eventIdTraceStorage = new ConcurrentHashMap<>();\n\n // Session ID -> Trace IDs -> Trace Object\n private final Map> sessionToTraceIdsMap = new ConcurrentHashMap<>();\n\n private final List allExportedSpans = Collections.synchronizedList(new ArrayList<>());\n\n public ApiServerSpanExporter() {}\n\n public Map getEventTraceAttributes(String eventId) {\n return this.eventIdTraceStorage.get(eventId);\n }\n\n public Map> getSessionToTraceIdsMap() {\n return this.sessionToTraceIdsMap;\n }\n\n public List getAllExportedSpans() {\n return this.allExportedSpans;\n }\n\n @Override\n public CompletableResultCode export(Collection spans) {\n exporterLog.debug(\"ApiServerSpanExporter received {} spans to export.\", spans.size());\n List currentBatch = new ArrayList<>(spans);\n allExportedSpans.addAll(currentBatch);\n\n for (SpanData span : currentBatch) {\n String spanName = span.getName();\n if (\"call_llm\".equals(spanName)\n || \"send_data\".equals(spanName)\n || (spanName != null && spanName.startsWith(\"tool_response\"))) {\n String eventId =\n span.getAttributes().get(AttributeKey.stringKey(\"gcp.vertex.agent.event_id\"));\n if (eventId != null && !eventId.isEmpty()) {\n Map attributesMap = new HashMap<>();\n span.getAttributes().forEach((key, value) -> attributesMap.put(key.getKey(), value));\n attributesMap.put(\"trace_id\", span.getSpanContext().getTraceId());\n attributesMap.put(\"span_id\", span.getSpanContext().getSpanId());\n attributesMap.putIfAbsent(\"gcp.vertex.agent.event_id\", eventId);\n exporterLog.debug(\"Storing event-based trace attributes for event_id: {}\", eventId);\n this.eventIdTraceStorage.put(eventId, attributesMap); // Use internal storage\n } else {\n exporterLog.trace(\n \"Span {} for event-based trace did not have 'gcp.vertex.agent.event_id'\"\n + \" attribute or it was empty.\",\n spanName);\n }\n }\n\n if (\"call_llm\".equals(spanName)) {\n String sessionId =\n span.getAttributes().get(AttributeKey.stringKey(\"gcp.vertex.agent.session_id\"));\n if (sessionId != null && !sessionId.isEmpty()) {\n String traceId = span.getSpanContext().getTraceId();\n sessionToTraceIdsMap\n .computeIfAbsent(sessionId, k -> Collections.synchronizedList(new ArrayList<>()))\n .add(traceId);\n exporterLog.trace(\n \"Associated trace_id {} with session_id {} for session tracing\",\n traceId,\n sessionId);\n } else {\n exporterLog.trace(\n \"Span {} for session trace did not have 'gcp.vertex.agent.session_id' attribute.\",\n spanName);\n }\n }\n }\n return CompletableResultCode.ofSuccess();\n }\n\n @Override\n public CompletableResultCode flush() {\n return CompletableResultCode.ofSuccess();\n }\n\n @Override\n public CompletableResultCode shutdown() {\n exporterLog.debug(\"Shutting down ApiServerSpanExporter.\");\n // no need to clear storage on shutdown, as everything is currently stored in memory.\n return CompletableResultCode.ofSuccess();\n }\n }\n\n /**\n * Data Transfer Object (DTO) for POST /run and POST /run-sse requests. Contains information\n * needed to execute an agent run.\n */\n public static class AgentRunRequest {\n @JsonProperty(\"appName\")\n public String appName;\n\n @JsonProperty(\"userId\")\n public String userId;\n\n @JsonProperty(\"sessionId\")\n public String sessionId;\n\n @JsonProperty(\"newMessage\")\n public Content newMessage;\n\n @JsonProperty(\"streaming\")\n public boolean streaming = false;\n\n public AgentRunRequest() {}\n\n public String getAppName() {\n return appName;\n }\n\n public String getUserId() {\n return userId;\n }\n\n public String getSessionId() {\n return sessionId;\n }\n\n public Content getNewMessage() {\n return newMessage;\n }\n\n public boolean getStreaming() {\n return streaming;\n }\n }\n\n /**\n * DTO for POST /apps/{appName}/eval_sets/{evalSetId}/add-session requests. Contains information\n * to associate a session with an evaluation set.\n */\n public static class AddSessionToEvalSetRequest {\n @JsonProperty(\"evalId\")\n public String evalId;\n\n @JsonProperty(\"sessionId\")\n public String sessionId;\n\n @JsonProperty(\"userId\")\n public String userId;\n\n public AddSessionToEvalSetRequest() {}\n\n public String getEvalId() {\n return evalId;\n }\n\n public String getSessionId() {\n return sessionId;\n }\n\n public String getUserId() {\n return userId;\n }\n }\n\n /**\n * DTO for POST /apps/{appName}/eval_sets/{evalSetId}/run-eval requests. Contains information for\n * running evaluations.\n */\n public static class RunEvalRequest {\n @JsonProperty(\"evalIds\")\n public List evalIds;\n\n @JsonProperty(\"evalMetrics\")\n public List evalMetrics;\n\n public RunEvalRequest() {}\n\n public List getEvalIds() {\n return evalIds;\n }\n\n public List getEvalMetrics() {\n return evalMetrics;\n }\n }\n\n /**\n * DTO for the response of POST /apps/{appName}/eval_sets/{evalSetId}/run-eval. Contains the\n * results of an evaluation run.\n */\n public static class RunEvalResult extends JsonBaseModel {\n @JsonProperty(\"appName\")\n public String appName;\n\n @JsonProperty(\"evalSetId\")\n public String evalSetId;\n\n @JsonProperty(\"evalId\")\n public String evalId;\n\n @JsonProperty(\"finalEvalStatus\")\n public String finalEvalStatus;\n\n @JsonProperty(\"evalMetricResults\")\n public List> evalMetricResults;\n\n @JsonProperty(\"sessionId\")\n public String sessionId;\n\n /**\n * Constructs a RunEvalResult.\n *\n * @param appName The application name.\n * @param evalSetId The evaluation set ID.\n * @param evalId The evaluation ID.\n * @param finalEvalStatus The final status of the evaluation.\n * @param evalMetricResults The results for each metric.\n * @param sessionId The session ID associated with the evaluation.\n */\n public RunEvalResult(\n String appName,\n String evalSetId,\n String evalId,\n String finalEvalStatus,\n List> evalMetricResults,\n String sessionId) {\n this.appName = appName;\n this.evalSetId = evalSetId;\n this.evalId = evalId;\n this.finalEvalStatus = finalEvalStatus;\n this.evalMetricResults = evalMetricResults;\n this.sessionId = sessionId;\n }\n\n public RunEvalResult() {}\n }\n\n /**\n * DTO for the response of GET\n * /apps/{appName}/users/{userId}/sessions/{sessionId}/events/{eventId}/graph. Contains the graph\n * representation (e.g., DOT source).\n */\n public static class GraphResponse {\n @JsonProperty(\"dotSrc\")\n public String dotSrc;\n\n /**\n * Constructs a GraphResponse.\n *\n * @param dotSrc The graph source string (e.g., in DOT format).\n */\n public GraphResponse(String dotSrc) {\n this.dotSrc = dotSrc;\n }\n\n public GraphResponse() {}\n\n public String getDotSrc() {\n return dotSrc;\n }\n }\n\n /**\n * Configures resource handlers for serving static content (like the Dev UI). Maps requests\n * starting with \"/dev-ui/\" to the directory specified by the 'adk.web.ui.dir' system property.\n */\n @Override\n public void addResourceHandlers(ResourceHandlerRegistry registry) {\n if (webUiDir != null && !webUiDir.isEmpty()) {\n // Ensure the path uses forward slashes and ends with a slash\n String location = webUiDir.replace(\"\\\\\", \"/\");\n if (!location.startsWith(\"file:\")) {\n location = \"file:\" + location; // Ensure file: prefix\n }\n if (!location.endsWith(\"/\")) {\n location += \"/\";\n }\n log.debug(\"Mapping URL path /** to static resources at location: {}\", location);\n registry\n .addResourceHandler(\"/**\")\n .addResourceLocations(location)\n .setCachePeriod(0)\n .resourceChain(true);\n\n } else {\n log.debug(\n \"System property 'adk.web.ui.dir' or config 'adk.web.ui.dir' is not set. Mapping URL path\"\n + \" /** to classpath:/browser/\");\n registry\n .addResourceHandler(\"/**\")\n .addResourceLocations(\"classpath:/browser/\")\n .setCachePeriod(0)\n .resourceChain(true);\n }\n }\n\n /**\n * Configures simple automated controllers: - Redirects the root path \"/\" to \"/dev-ui\". - Forwards\n * requests to \"/dev-ui\" to \"/dev-ui/index.html\" so the ResourceHandler serves it.\n */\n @Override\n public void addViewControllers(ViewControllerRegistry registry) {\n registry.addRedirectViewController(\"/\", \"/dev-ui\");\n registry.addViewController(\"/dev-ui\").setViewName(\"forward:/index.html\");\n registry.addViewController(\"/dev-ui/\").setViewName(\"forward:/index.html\");\n }\n\n /** Spring Boot REST Controller handling agent-related API endpoints. */\n @RestController\n public static class AgentController {\n\n private static final Logger log = LoggerFactory.getLogger(AgentController.class);\n\n private static final String EVAL_SESSION_ID_PREFIX = \"ADK_EVAL_\";\n\n private final BaseSessionService sessionService;\n private final BaseArtifactService artifactService;\n private final Map agentRegistry;\n private final ApiServerSpanExporter apiServerSpanExporter;\n private final RunnerService runnerService;\n private final ExecutorService sseExecutor = Executors.newCachedThreadPool();\n\n /**\n * Constructs the AgentController.\n *\n * @param sessionService The service for managing sessions.\n * @param artifactService The service for managing artifacts.\n * @param agentRegistry The registry of loaded agents.\n * @param apiServerSpanExporter The exporter holding all trace data.\n * @param runnerService The service for obtaining Runner instances.\n */\n @Autowired\n public AgentController(\n BaseSessionService sessionService,\n BaseArtifactService artifactService,\n @Qualifier(\"loadedAgentRegistry\") Map agentRegistry,\n ApiServerSpanExporter apiServerSpanExporter,\n RunnerService runnerService) {\n this.sessionService = sessionService;\n this.artifactService = artifactService;\n this.agentRegistry = agentRegistry;\n this.apiServerSpanExporter = apiServerSpanExporter;\n this.runnerService = runnerService;\n log.info(\n \"AgentController initialized with {} dynamic agents: {}\",\n agentRegistry.size(),\n agentRegistry.keySet());\n if (agentRegistry.isEmpty()) {\n log.warn(\n \"Agent registry is empty. Check 'adk.agents.source-dir' property and compilation\"\n + \" logs.\");\n }\n }\n\n /**\n * Finds a session by its identifiers or throws a ResponseStatusException if not found or if\n * there's an app/user mismatch.\n *\n * @param appName The application name.\n * @param userId The user ID.\n * @param sessionId The session ID.\n * @return The found Session object.\n * @throws ResponseStatusException with HttpStatus.NOT_FOUND if the session doesn't exist or\n * belongs to a different app/user.\n */\n private Session findSessionOrThrow(String appName, String userId, String sessionId) {\n Maybe maybeSession =\n sessionService.getSession(appName, userId, sessionId, Optional.empty());\n\n Session session = maybeSession.blockingGet();\n\n if (session == null) {\n log.warn(\n \"Session not found for appName={}, userId={}, sessionId={}\",\n appName,\n userId,\n sessionId);\n throw new ResponseStatusException(\n HttpStatus.NOT_FOUND,\n String.format(\n \"Session not found: appName=%s, userId=%s, sessionId=%s\",\n appName, userId, sessionId));\n }\n\n if (!Objects.equals(session.appName(), appName)\n || !Objects.equals(session.userId(), userId)) {\n log.warn(\n \"Session ID {} found but appName/userId mismatch (Expected: {}/{}, Found: {}/{}) -\"\n + \" Treating as not found.\",\n sessionId,\n appName,\n userId,\n session.appName(),\n session.userId());\n\n throw new ResponseStatusException(\n HttpStatus.NOT_FOUND, \"Session found but belongs to a different app/user.\");\n }\n log.debug(\"Found session: {}\", sessionId);\n return session;\n }\n\n /**\n * Lists available applications. Currently returns only the configured root agent's name.\n *\n * @return A list containing the root agent's name.\n */\n @GetMapping(\"/list-apps\")\n public List listApps() {\n log.info(\"Listing apps from dynamic registry. Found: {}\", agentRegistry.keySet());\n List appNames = new ArrayList<>(agentRegistry.keySet());\n Collections.sort(appNames);\n return appNames;\n }\n\n /**\n * Endpoint for retrieving trace information stored by the ApiServerSpanExporter, based on event\n * ID.\n *\n * @param eventId The ID of the event to trace (expected to be gcp.vertex.agent.event_id).\n * @return A ResponseEntity containing the trace data or NOT_FOUND.\n */\n @GetMapping(\"/debug/trace/{eventId}\")\n public ResponseEntity getTraceDict(@PathVariable String eventId) {\n log.info(\"Request received for GET /debug/trace/{}\", eventId);\n Map traceData = this.apiServerSpanExporter.getEventTraceAttributes(eventId);\n if (traceData == null) {\n log.warn(\"Trace not found for eventId: {}\", eventId);\n return ResponseEntity.status(HttpStatus.NOT_FOUND)\n .body(Collections.singletonMap(\"message\", \"Trace not found for eventId: \" + eventId));\n }\n log.info(\"Returning trace data for eventId: {}\", eventId);\n return ResponseEntity.ok(traceData);\n }\n\n /**\n * Retrieves trace spans for a given session ID.\n *\n * @param sessionId The session ID.\n * @return A ResponseEntity containing a list of span data maps for the session, or an empty\n * list.\n */\n @GetMapping(\"/debug/trace/session/{sessionId}\")\n public ResponseEntity getSessionTrace(@PathVariable String sessionId) {\n log.info(\"Request received for GET /debug/trace/session/{}\", sessionId);\n\n List traceIdsForSession =\n this.apiServerSpanExporter.getSessionToTraceIdsMap().get(sessionId);\n\n if (traceIdsForSession == null || traceIdsForSession.isEmpty()) {\n log.warn(\"No trace IDs found for session ID: {}\", sessionId);\n return ResponseEntity.ok(Collections.emptyList());\n }\n\n // Iterate over a snapshot of all spans to avoid concurrent modification issues\n // if the exporter is actively adding spans.\n List allSpansSnapshot =\n new ArrayList<>(this.apiServerSpanExporter.getAllExportedSpans());\n\n if (allSpansSnapshot.isEmpty()) {\n log.warn(\"No spans have been exported yet overall.\");\n return ResponseEntity.ok(Collections.emptyList());\n }\n\n Set relevantTraceIds = new HashSet<>(traceIdsForSession);\n List> resultSpans = new ArrayList<>();\n\n for (SpanData span : allSpansSnapshot) {\n if (relevantTraceIds.contains(span.getSpanContext().getTraceId())) {\n Map spanMap = new HashMap<>();\n spanMap.put(\"name\", span.getName());\n spanMap.put(\"span_id\", span.getSpanContext().getSpanId());\n spanMap.put(\"trace_id\", span.getSpanContext().getTraceId());\n spanMap.put(\"start_time\", span.getStartEpochNanos());\n spanMap.put(\"end_time\", span.getEndEpochNanos());\n\n Map attributesMap = new HashMap<>();\n span.getAttributes().forEach((key, value) -> attributesMap.put(key.getKey(), value));\n spanMap.put(\"attributes\", attributesMap);\n\n String parentSpanId = span.getParentSpanId();\n if (SpanId.isValid(parentSpanId)) {\n spanMap.put(\"parent_span_id\", parentSpanId);\n } else {\n spanMap.put(\"parent_span_id\", null);\n }\n resultSpans.add(spanMap);\n }\n }\n\n log.info(\"Returning {} spans for session ID: {}\", resultSpans.size(), sessionId);\n return ResponseEntity.ok(resultSpans);\n }\n\n /**\n * Retrieves a specific session by its ID.\n *\n * @param appName The application name.\n * @param userId The user ID.\n * @param sessionId The session ID.\n * @return The requested Session object.\n * @throws ResponseStatusException if the session is not found.\n */\n @GetMapping(\"/apps/{appName}/users/{userId}/sessions/{sessionId}\")\n public Session getSession(\n @PathVariable String appName, @PathVariable String userId, @PathVariable String sessionId) {\n log.info(\n \"Request received for GET /apps/{}/users/{}/sessions/{}\", appName, userId, sessionId);\n return findSessionOrThrow(appName, userId, sessionId);\n }\n\n /**\n * Lists all non-evaluation sessions for a given app and user.\n *\n * @param appName The name of the application.\n * @param userId The ID of the user.\n * @return A list of sessions, excluding those used for evaluation.\n */\n @GetMapping(\"/apps/{appName}/users/{userId}/sessions\")\n public List listSessions(@PathVariable String appName, @PathVariable String userId) {\n log.info(\"Request received for GET /apps/{}/users/{}/sessions\", appName, userId);\n\n Single sessionsResponseSingle =\n sessionService.listSessions(appName, userId);\n\n ListSessionsResponse response = sessionsResponseSingle.blockingGet();\n if (response == null || response.sessions() == null) {\n log.warn(\n \"Received null response or null sessions list for listSessions({}, {})\",\n appName,\n userId);\n return Collections.emptyList();\n }\n\n List filteredSessions =\n response.sessions().stream()\n .filter(s -> !s.id().startsWith(EVAL_SESSION_ID_PREFIX))\n .collect(Collectors.toList());\n log.info(\n \"Found {} non-evaluation sessions for app={}, user={}\",\n filteredSessions.size(),\n appName,\n userId);\n return filteredSessions;\n }\n\n /**\n * Creates a new session with a specific ID provided by the client.\n *\n * @param appName The application name.\n * @param userId The user ID.\n * @param sessionId The desired session ID.\n * @param state Optional initial state for the session.\n * @return The newly created Session object.\n * @throws ResponseStatusException if a session with the given ID already exists (BAD_REQUEST)\n * or if creation fails (INTERNAL_SERVER_ERROR).\n */\n @PostMapping(\"/apps/{appName}/users/{userId}/sessions/{sessionId}\")\n public Session createSessionWithId(\n @PathVariable String appName,\n @PathVariable String userId,\n @PathVariable String sessionId,\n @RequestBody(required = false) Map state) {\n log.info(\n \"Request received for POST /apps/{}/users/{}/sessions/{} with state: {}\",\n appName,\n userId,\n sessionId,\n state);\n\n try {\n findSessionOrThrow(appName, userId, sessionId);\n\n log.warn(\"Attempted to create session with existing ID: {}\", sessionId);\n throw new ResponseStatusException(\n HttpStatus.BAD_REQUEST, \"Session already exists: \" + sessionId);\n } catch (ResponseStatusException e) {\n\n if (e.getStatusCode() != HttpStatus.NOT_FOUND) {\n throw e;\n }\n\n log.info(\"Session {} not found, proceeding with creation.\", sessionId);\n }\n\n Map initialState = (state != null) ? state : Collections.emptyMap();\n try {\n Session createdSession =\n sessionService\n .createSession(appName, userId, new ConcurrentHashMap<>(initialState), sessionId)\n .blockingGet();\n\n if (createdSession == null) {\n\n log.error(\n \"Session creation call completed without error but returned null session for {}\",\n sessionId);\n throw new ResponseStatusException(\n HttpStatus.INTERNAL_SERVER_ERROR, \"Failed to create session (null result)\");\n }\n log.info(\"Session created successfully with id: {}\", createdSession.id());\n return createdSession;\n } catch (Exception e) {\n log.error(\"Error creating session with id {}\", sessionId, e);\n\n throw new ResponseStatusException(\n HttpStatus.INTERNAL_SERVER_ERROR, \"Error creating session\", e);\n }\n }\n\n /**\n * Creates a new session where the ID is generated by the service.\n *\n * @param appName The application name.\n * @param userId The user ID.\n * @param state Optional initial state for the session.\n * @return The newly created Session object.\n * @throws ResponseStatusException if creation fails (INTERNAL_SERVER_ERROR).\n */\n @PostMapping(\"/apps/{appName}/users/{userId}/sessions\")\n public Session createSession(\n @PathVariable String appName,\n @PathVariable String userId,\n @RequestBody(required = false) Map state) {\n\n log.info(\n \"Request received for POST /apps/{}/users/{}/sessions (service generates ID) with state:\"\n + \" {}\",\n appName,\n userId,\n state);\n\n Map initialState = (state != null) ? state : Collections.emptyMap();\n try {\n\n Session createdSession =\n sessionService\n .createSession(appName, userId, new ConcurrentHashMap<>(initialState), null)\n .blockingGet();\n\n if (createdSession == null) {\n log.error(\n \"Session creation call completed without error but returned null session for user {}\",\n userId);\n throw new ResponseStatusException(\n HttpStatus.INTERNAL_SERVER_ERROR, \"Failed to create session (null result)\");\n }\n log.info(\"Session created successfully with generated id: {}\", createdSession.id());\n return createdSession;\n } catch (Exception e) {\n log.error(\"Error creating session for user {}\", userId, e);\n throw new ResponseStatusException(\n HttpStatus.INTERNAL_SERVER_ERROR, \"Error creating session\", e);\n }\n }\n\n /**\n * Deletes a specific session.\n *\n * @param appName The application name.\n * @param userId The user ID.\n * @param sessionId The session ID to delete.\n * @return A ResponseEntity with status NO_CONTENT on success.\n * @throws ResponseStatusException if deletion fails (INTERNAL_SERVER_ERROR).\n */\n @DeleteMapping(\"/apps/{appName}/users/{userId}/sessions/{sessionId}\")\n public ResponseEntity deleteSession(\n @PathVariable String appName, @PathVariable String userId, @PathVariable String sessionId) {\n log.info(\n \"Request received for DELETE /apps/{}/users/{}/sessions/{}\", appName, userId, sessionId);\n try {\n\n sessionService.deleteSession(appName, userId, sessionId).blockingAwait();\n log.info(\"Session deleted successfully: {}\", sessionId);\n return ResponseEntity.noContent().build();\n } catch (Exception e) {\n\n log.error(\"Error deleting session {}\", sessionId, e);\n\n throw new ResponseStatusException(\n HttpStatus.INTERNAL_SERVER_ERROR, \"Error deleting session\", e);\n }\n }\n\n /**\n * Loads the latest or a specific version of an artifact associated with a session.\n *\n * @param appName The application name.\n * @param userId The user ID.\n * @param sessionId The session ID.\n * @param artifactName The name of the artifact.\n * @param version Optional specific version number. If null, loads the latest.\n * @return The artifact content as a Part object.\n * @throws ResponseStatusException if the artifact is not found (NOT_FOUND).\n */\n @GetMapping(\"/apps/{appName}/users/{userId}/sessions/{sessionId}/artifacts/{artifactName}\")\n public Part loadArtifact(\n @PathVariable String appName,\n @PathVariable String userId,\n @PathVariable String sessionId,\n @PathVariable String artifactName,\n @RequestParam(required = false) Integer version) {\n String versionStr = (version == null) ? \"latest\" : String.valueOf(version);\n log.info(\n \"Request received to load artifact: app={}, user={}, session={}, artifact={}, version={}\",\n appName,\n userId,\n sessionId,\n artifactName,\n versionStr);\n\n Maybe artifactMaybe =\n artifactService.loadArtifact(\n appName, userId, sessionId, artifactName, Optional.ofNullable(version));\n\n Part artifact = artifactMaybe.blockingGet();\n\n if (artifact == null) {\n log.warn(\n \"Artifact not found: app={}, user={}, session={}, artifact={}, version={}\",\n appName,\n userId,\n sessionId,\n artifactName,\n versionStr);\n throw new ResponseStatusException(HttpStatus.NOT_FOUND, \"Artifact not found\");\n }\n log.debug(\"Artifact {} version {} loaded successfully.\", artifactName, versionStr);\n return artifact;\n }\n\n /**\n * Loads a specific version of an artifact.\n *\n * @param appName The application name.\n * @param userId The user ID.\n * @param sessionId The session ID.\n * @param artifactName The name of the artifact.\n * @param versionId The specific version number.\n * @return The artifact content as a Part object.\n * @throws ResponseStatusException if the artifact version is not found (NOT_FOUND).\n */\n @GetMapping(\n \"/apps/{appName}/users/{userId}/sessions/{sessionId}/artifacts/{artifactName}/versions/{versionId}\")\n public Part loadArtifactVersion(\n @PathVariable String appName,\n @PathVariable String userId,\n @PathVariable String sessionId,\n @PathVariable String artifactName,\n @PathVariable int versionId) {\n log.info(\n \"Request received to load artifact version: app={}, user={}, session={}, artifact={},\"\n + \" version={}\",\n appName,\n userId,\n sessionId,\n artifactName,\n versionId);\n\n Maybe artifactMaybe =\n artifactService.loadArtifact(\n appName, userId, sessionId, artifactName, Optional.of(versionId));\n\n Part artifact = artifactMaybe.blockingGet();\n\n if (artifact == null) {\n log.warn(\n \"Artifact version not found: app={}, user={}, session={}, artifact={}, version={}\",\n appName,\n userId,\n sessionId,\n artifactName,\n versionId);\n throw new ResponseStatusException(HttpStatus.NOT_FOUND, \"Artifact version not found\");\n }\n log.debug(\"Artifact {} version {} loaded successfully.\", artifactName, versionId);\n return artifact;\n }\n\n /**\n * Lists the names of all artifacts associated with a session.\n *\n * @param appName The application name.\n * @param userId The user ID.\n * @param sessionId The session ID.\n * @return A list of artifact names.\n */\n @GetMapping(\"/apps/{appName}/users/{userId}/sessions/{sessionId}/artifacts\")\n public List listArtifactNames(\n @PathVariable String appName, @PathVariable String userId, @PathVariable String sessionId) {\n log.info(\n \"Request received to list artifact names for app={}, user={}, session={}\",\n appName,\n userId,\n sessionId);\n\n Single responseSingle =\n artifactService.listArtifactKeys(appName, userId, sessionId);\n\n ListArtifactsResponse response = responseSingle.blockingGet();\n List filenames =\n (response != null && response.filenames() != null)\n ? response.filenames()\n : Collections.emptyList();\n log.info(\"Found {} artifact names for session {}\", filenames.size(), sessionId);\n return filenames;\n }\n\n /**\n * Lists the available versions for a specific artifact.\n *\n * @param appName The application name.\n * @param userId The user ID.\n * @param sessionId The session ID.\n * @param artifactName The name of the artifact.\n * @return A list of version numbers (integers).\n */\n @GetMapping(\n \"/apps/{appName}/users/{userId}/sessions/{sessionId}/artifacts/{artifactName}/versions\")\n public List listArtifactVersions(\n @PathVariable String appName,\n @PathVariable String userId,\n @PathVariable String sessionId,\n @PathVariable String artifactName) {\n log.info(\n \"Request received to list versions for artifact: app={}, user={}, session={},\"\n + \" artifact={}\",\n appName,\n userId,\n sessionId,\n artifactName);\n\n Single> versionsSingle =\n artifactService.listVersions(appName, userId, sessionId, artifactName);\n ImmutableList versions = versionsSingle.blockingGet();\n log.info(\n \"Found {} versions for artifact {}\",\n versions != null ? versions.size() : 0,\n artifactName);\n return versions != null ? versions : Collections.emptyList();\n }\n\n /**\n * Deletes an artifact and all its versions.\n *\n * @param appName The application name.\n * @param userId The user ID.\n * @param sessionId The session ID.\n * @param artifactName The name of the artifact to delete.\n * @return A ResponseEntity with status NO_CONTENT on success.\n * @throws ResponseStatusException if deletion fails (INTERNAL_SERVER_ERROR).\n */\n @DeleteMapping(\"/apps/{appName}/users/{userId}/sessions/{sessionId}/artifacts/{artifactName}\")\n public ResponseEntity deleteArtifact(\n @PathVariable String appName,\n @PathVariable String userId,\n @PathVariable String sessionId,\n @PathVariable String artifactName) {\n log.info(\n \"Request received to delete artifact: app={}, user={}, session={}, artifact={}\",\n appName,\n userId,\n sessionId,\n artifactName);\n\n try {\n\n artifactService.deleteArtifact(appName, userId, sessionId, artifactName);\n log.info(\"Artifact deleted successfully: {}\", artifactName);\n return ResponseEntity.noContent().build();\n } catch (Exception e) {\n log.error(\"Error deleting artifact {}\", artifactName, e);\n\n throw new ResponseStatusException(\n HttpStatus.INTERNAL_SERVER_ERROR, \"Error deleting artifact\", e);\n }\n }\n\n /**\n * Executes a non-streaming agent run for a given session and message.\n *\n * @param request The AgentRunRequest containing run details.\n * @return A list of events generated during the run.\n * @throws ResponseStatusException if the session is not found or the run fails.\n */\n @PostMapping(\"/run\")\n public List agentRun(@RequestBody AgentRunRequest request) {\n if (request.appName == null || request.appName.trim().isEmpty()) {\n log.warn(\"appName cannot be null or empty in POST /run request.\");\n throw new ResponseStatusException(\n HttpStatus.BAD_REQUEST, \"appName cannot be null or empty\");\n }\n if (request.sessionId == null || request.sessionId.trim().isEmpty()) {\n log.warn(\"sessionId cannot be null or empty in POST /run request.\");\n throw new ResponseStatusException(\n HttpStatus.BAD_REQUEST, \"sessionId cannot be null or empty\");\n }\n log.info(\"Request received for POST /run for session: {}\", request.sessionId);\n\n Runner runner = this.runnerService.getRunner(request.appName);\n try {\n\n RunConfig runConfig = RunConfig.builder().setStreamingMode(StreamingMode.NONE).build();\n Flowable eventStream =\n runner.runAsync(request.userId, request.sessionId, request.newMessage, runConfig);\n\n List events = Lists.newArrayList(eventStream.blockingIterable());\n log.info(\"Agent run for session {} generated {} events.\", request.sessionId, events.size());\n return events;\n } catch (Exception e) {\n log.error(\"Error during agent run for session {}\", request.sessionId, e);\n throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, \"Agent run failed\", e);\n }\n }\n\n /**\n * Executes an agent run and streams the resulting events using Server-Sent Events (SSE).\n *\n * @param request The AgentRunRequest containing run details.\n * @return A Flux that will stream events to the client.\n */\n @PostMapping(value = \"/run_sse\", produces = MediaType.TEXT_EVENT_STREAM_VALUE)\n public SseEmitter agentRunSse(@RequestBody AgentRunRequest request) {\n SseEmitter emitter = new SseEmitter();\n\n if (request.appName == null || request.appName.trim().isEmpty()) {\n log.warn(\n \"appName cannot be null or empty in SseEmitter request for appName: {}, session: {}\",\n request.appName,\n request.sessionId);\n emitter.completeWithError(\n new ResponseStatusException(HttpStatus.BAD_REQUEST, \"appName cannot be null or empty\"));\n return emitter;\n }\n if (request.sessionId == null || request.sessionId.trim().isEmpty()) {\n log.warn(\n \"sessionId cannot be null or empty in SseEmitter request for appName: {}, session: {}\",\n request.appName,\n request.sessionId);\n emitter.completeWithError(\n new ResponseStatusException(\n HttpStatus.BAD_REQUEST, \"sessionId cannot be null or empty\"));\n return emitter;\n }\n\n log.info(\n \"SseEmitter Request received for POST /run_sse_emitter for session: {}\",\n request.sessionId);\n\n final String sessionId = request.sessionId;\n sseExecutor.execute(\n () -> {\n Runner runner;\n try {\n runner = this.runnerService.getRunner(request.appName);\n } catch (ResponseStatusException e) {\n log.warn(\n \"Setup failed for SseEmitter request for session {}: {}\",\n sessionId,\n e.getMessage());\n try {\n emitter.completeWithError(e);\n } catch (Exception ex) {\n log.warn(\n \"Error completing emitter after setup failure for session {}: {}\",\n sessionId,\n ex.getMessage());\n }\n return;\n }\n\n final RunConfig runConfig =\n RunConfig.builder()\n .setStreamingMode(\n request.getStreaming() ? StreamingMode.SSE : StreamingMode.NONE)\n .build();\n\n Flowable eventFlowable =\n runner.runAsync(request.userId, request.sessionId, request.newMessage, runConfig);\n\n Disposable disposable =\n eventFlowable\n .observeOn(Schedulers.io())\n .subscribe(\n event -> {\n try {\n log.debug(\n \"SseEmitter: Sending event {} for session {}\",\n event.id(),\n sessionId);\n emitter.send(SseEmitter.event().data(event.toJson()));\n } catch (IOException e) {\n log.error(\n \"SseEmitter: IOException sending event for session {}: {}\",\n sessionId,\n e.getMessage());\n throw new RuntimeException(\"Failed to send event\", e);\n } catch (Exception e) {\n log.error(\n \"SseEmitter: Unexpected error sending event for session {}: {}\",\n sessionId,\n e.getMessage(),\n e);\n throw new RuntimeException(\"Unexpected error sending event\", e);\n }\n },\n error -> {\n log.error(\n \"SseEmitter: Stream error for session {}: {}\",\n sessionId,\n error.getMessage(),\n error);\n try {\n emitter.completeWithError(error);\n } catch (Exception ex) {\n log.warn(\n \"Error completing emitter after stream error for session {}: {}\",\n sessionId,\n ex.getMessage());\n }\n },\n () -> {\n log.debug(\n \"SseEmitter: Stream completed normally for session: {}\", sessionId);\n try {\n emitter.complete();\n } catch (Exception ex) {\n log.warn(\n \"Error completing emitter after normal completion for session {}:\"\n + \" {}\",\n sessionId,\n ex.getMessage());\n }\n });\n emitter.onCompletion(\n () -> {\n log.debug(\n \"SseEmitter: onCompletion callback for session: {}. Disposing subscription.\",\n sessionId);\n if (!disposable.isDisposed()) {\n disposable.dispose();\n }\n });\n emitter.onTimeout(\n () -> {\n log.debug(\n \"SseEmitter: onTimeout callback for session: {}. Disposing subscription and\"\n + \" completing.\",\n sessionId);\n if (!disposable.isDisposed()) {\n disposable.dispose();\n }\n emitter.complete();\n });\n });\n\n log.debug(\"SseEmitter: Returning emitter for session: {}\", sessionId);\n return emitter;\n }\n\n /**\n * Endpoint to get a graph representation of an event (currently returns a placeholder).\n * Requires Graphviz or similar tooling for full implementation.\n *\n * @param appName Application name.\n * @param userId User ID.\n * @param sessionId Session ID.\n * @param eventId Event ID.\n * @return ResponseEntity containing a GraphResponse with placeholder DOT source.\n * @throws ResponseStatusException if the session or event is not found.\n */\n @GetMapping(\"/apps/{appName}/users/{userId}/sessions/{sessionId}/events/{eventId}/graph\")\n public ResponseEntity getEventGraph(\n @PathVariable String appName,\n @PathVariable String userId,\n @PathVariable String sessionId,\n @PathVariable String eventId) {\n log.info(\n \"Request received for GET /apps/{}/users/{}/sessions/{}/events/{}/graph\",\n appName,\n userId,\n sessionId,\n eventId);\n\n BaseAgent currentAppAgent = agentRegistry.get(appName);\n if (currentAppAgent == null) {\n log.warn(\"Agent app '{}' not found for graph generation.\", appName);\n return ResponseEntity.status(HttpStatus.NOT_FOUND)\n .body(new GraphResponse(\"Agent app not found: \" + appName));\n }\n\n Session session = findSessionOrThrow(appName, userId, sessionId);\n Event event =\n session.events().stream()\n .filter(e -> Objects.equals(e.id(), eventId))\n .findFirst()\n .orElse(null);\n\n if (event == null) {\n log.warn(\"Event {} not found in session {}\", eventId, sessionId);\n return ResponseEntity.ok(new GraphResponse(null));\n }\n\n log.debug(\"Found event {} for graph generation.\", eventId);\n\n List> highlightPairs = new ArrayList<>();\n String eventAuthor = event.author();\n List functionCalls = event.functionCalls();\n List functionResponses = event.functionResponses();\n\n if (!functionCalls.isEmpty()) {\n log.debug(\"Processing {} function calls for highlighting.\", functionCalls.size());\n for (FunctionCall fc : functionCalls) {\n Optional toolName = fc.name();\n if (toolName.isPresent() && !toolName.get().isEmpty()) {\n highlightPairs.add(ImmutableList.of(eventAuthor, toolName.get()));\n log.trace(\"Adding function call highlight: {} -> {}\", eventAuthor, toolName.get());\n }\n }\n } else if (!functionResponses.isEmpty()) {\n log.debug(\"Processing {} function responses for highlighting.\", functionResponses.size());\n for (FunctionResponse fr : functionResponses) {\n Optional toolName = fr.name();\n if (toolName.isPresent() && !toolName.get().isEmpty()) {\n highlightPairs.add(ImmutableList.of(toolName.get(), eventAuthor));\n log.trace(\"Adding function response highlight: {} -> {}\", toolName.get(), eventAuthor);\n }\n }\n } else {\n log.debug(\"Processing simple event, highlighting author: {}\", eventAuthor);\n highlightPairs.add(ImmutableList.of(eventAuthor, eventAuthor));\n }\n\n Optional dotSourceOpt =\n AgentGraphGenerator.getAgentGraphDotSource(currentAppAgent, highlightPairs);\n\n if (dotSourceOpt.isPresent()) {\n log.debug(\"Successfully generated graph DOT source for event {}\", eventId);\n return ResponseEntity.ok(new GraphResponse(dotSourceOpt.get()));\n } else {\n log.warn(\n \"Failed to generate graph DOT source for event {} with agent {}\",\n eventId,\n currentAppAgent.name());\n return ResponseEntity.ok(new GraphResponse(\"Could not generate graph for this event.\"));\n }\n }\n\n /** Placeholder for creating an evaluation set. */\n @PostMapping(\"/apps/{appName}/eval_sets/{evalSetId}\")\n public ResponseEntity createEvalSet(\n @PathVariable String appName, @PathVariable String evalSetId) {\n log.warn(\"Endpoint /apps/{}/eval_sets/{} (POST) is not implemented\", appName, evalSetId);\n return ResponseEntity.status(HttpStatus.NOT_IMPLEMENTED)\n .body(Collections.singletonMap(\"message\", \"Eval set creation not implemented\"));\n }\n\n /** Placeholder for listing evaluation sets. */\n @GetMapping(\"/apps/{appName}/eval_sets\")\n public List listEvalSets(@PathVariable String appName) {\n log.warn(\"Endpoint /apps/{}/eval_sets (GET) is not implemented\", appName);\n return Collections.emptyList();\n }\n\n /** Placeholder for adding a session to an evaluation set. */\n @PostMapping(\"/apps/{appName}/eval_sets/{evalSetId}/add-session\")\n public ResponseEntity addSessionToEvalSet(\n @PathVariable String appName,\n @PathVariable String evalSetId,\n @RequestBody AddSessionToEvalSetRequest req) {\n log.warn(\n \"Endpoint /apps/{}/eval_sets/{}/add-session is not implemented. Request details:\"\n + \" evalId={}, sessionId={}, userId={}\",\n appName,\n evalSetId,\n req.getEvalId(),\n req.getSessionId(),\n req.getUserId());\n return ResponseEntity.status(HttpStatus.NOT_IMPLEMENTED)\n .body(Collections.singletonMap(\"message\", \"Adding session to eval set not implemented\"));\n }\n\n /** Placeholder for listing evaluations within an evaluation set. */\n @GetMapping(\"/apps/{appName}/eval_sets/{evalSetId}/evals\")\n public List listEvalsInEvalSet(\n @PathVariable String appName, @PathVariable String evalSetId) {\n log.warn(\"Endpoint /apps/{}/eval_sets/{}/evals is not implemented\", appName, evalSetId);\n return Collections.emptyList();\n }\n\n /** Placeholder for running evaluations. */\n @PostMapping(\"/apps/{appName}/eval_sets/{evalSetId}/run-eval\")\n public List runEval(\n @PathVariable String appName,\n @PathVariable String evalSetId,\n @RequestBody RunEvalRequest req) {\n log.warn(\n \"Endpoint /apps/{}/eval_sets/{}/run-eval is not implemented. Request details: evalIds={},\"\n + \" evalMetrics={}\",\n appName,\n evalSetId,\n req.getEvalIds(),\n req.getEvalMetrics());\n return Collections.emptyList();\n }\n\n /**\n * Gets a specific evaluation result. (STUB - Not Implemented)\n *\n * @param appName The application name.\n * @param evalResultId The evaluation result ID.\n * @return A ResponseEntity indicating the endpoint is not implemented.\n */\n @GetMapping(\"/apps/{appName}/eval_results/{evalResultId}\")\n public ResponseEntity getEvalResult(\n @PathVariable String appName, @PathVariable String evalResultId) {\n log.warn(\"Endpoint /apps/{}/eval_results/{} (GET) is not implemented\", appName, evalResultId);\n return ResponseEntity.status(HttpStatus.NOT_IMPLEMENTED)\n .body(Collections.singletonMap(\"message\", \"Get evaluation result not implemented\"));\n }\n\n /**\n * Lists all evaluation results for an app. (STUB - Not Implemented)\n *\n * @param appName The application name.\n * @return An empty list, as this endpoint is not implemented.\n */\n @GetMapping(\"/apps/{appName}/eval_results\")\n public List listEvalResults(@PathVariable String appName) {\n log.warn(\"Endpoint /apps/{}/eval_results (GET) is not implemented\", appName);\n return Collections.emptyList();\n }\n }\n\n /** Configuration class for WebSocket handling. */\n @Configuration\n @EnableWebSocket\n public static class WebSocketConfig implements WebSocketConfigurer {\n\n private final LiveWebSocketHandler liveWebSocketHandler;\n\n @Autowired\n public WebSocketConfig(LiveWebSocketHandler liveWebSocketHandler) {\n this.liveWebSocketHandler = liveWebSocketHandler;\n }\n\n @Override\n public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {\n registry.addHandler(liveWebSocketHandler, \"/run_live\").setAllowedOrigins(\"*\");\n }\n }\n\n /**\n * WebSocket Handler for the /run_live endpoint.\n *\n *

Manages bidirectional communication for live agent interactions. Assumes the\n * com.google.adk.runner.Runner class has a method: {@code public Flowable runLive(Session\n * session, Flowable liveRequests, List modalities)}\n */\n @Component\n public static class LiveWebSocketHandler extends TextWebSocketHandler {\n private static final Logger log = LoggerFactory.getLogger(LiveWebSocketHandler.class);\n private static final String LIVE_REQUEST_QUEUE_ATTR = \"liveRequestQueue\";\n private static final String LIVE_SUBSCRIPTION_ATTR = \"liveSubscription\";\n private static final int WEBSOCKET_MAX_BYTES_FOR_REASON = 123;\n\n private final ObjectMapper objectMapper;\n private final BaseSessionService sessionService;\n private final RunnerService runnerService;\n\n @Autowired\n public LiveWebSocketHandler(\n ObjectMapper objectMapper, BaseSessionService sessionService, RunnerService runnerService) {\n this.objectMapper = objectMapper;\n this.sessionService = sessionService;\n this.runnerService = runnerService;\n }\n\n @Override\n public void afterConnectionEstablished(WebSocketSession wsSession) throws Exception {\n URI uri = wsSession.getUri();\n if (uri == null) {\n log.warn(\"WebSocket session URI is null, cannot establish connection.\");\n wsSession.close(CloseStatus.SERVER_ERROR.withReason(\"Invalid URI\"));\n return;\n }\n String path = uri.getPath();\n log.info(\"WebSocket connection established: {} from {}\", wsSession.getId(), uri);\n\n MultiValueMap queryParams =\n UriComponentsBuilder.fromUri(uri).build().getQueryParams();\n String appName = queryParams.getFirst(\"app_name\");\n String userId = queryParams.getFirst(\"user_id\");\n String sessionId = queryParams.getFirst(\"session_id\");\n\n if (appName == null || appName.trim().isEmpty()) {\n log.warn(\n \"WebSocket connection for session {} rejected: app_name query parameter is required and\"\n + \" cannot be empty. URI: {}\",\n wsSession.getId(),\n uri);\n wsSession.close(\n CloseStatus.POLICY_VIOLATION.withReason(\n \"app_name query parameter is required and cannot be empty\"));\n return;\n }\n if (sessionId == null || sessionId.trim().isEmpty()) {\n log.warn(\n \"WebSocket connection for session {} rejected: session_id query parameter is required\"\n + \" and cannot be empty. URI: {}\",\n wsSession.getId(),\n uri);\n wsSession.close(\n CloseStatus.POLICY_VIOLATION.withReason(\n \"session_id query parameter is required and cannot be empty\"));\n return;\n }\n\n log.debug(\n \"Extracted params for WebSocket session {}: appName={}, userId={}, sessionId={},\",\n wsSession.getId(),\n appName,\n userId,\n sessionId);\n\n RunConfig runConfig =\n RunConfig.builder()\n .setResponseModalities(ImmutableList.of(new Modality(Modality.Known.AUDIO)))\n .setStreamingMode(StreamingMode.BIDI)\n .build();\n\n Session session;\n try {\n session =\n sessionService.getSession(appName, userId, sessionId, Optional.empty()).blockingGet();\n if (session == null) {\n log.warn(\n \"Session not found for WebSocket: app={}, user={}, id={}. Closing connection.\",\n appName,\n userId,\n sessionId);\n wsSession.close(new CloseStatus(1002, \"Session not found\")); // 1002: Protocol Error\n return;\n }\n } catch (Exception e) {\n log.error(\n \"Error retrieving session for WebSocket: app={}, user={}, id={}\",\n appName,\n userId,\n sessionId,\n e);\n wsSession.close(CloseStatus.SERVER_ERROR.withReason(\"Failed to retrieve session\"));\n return;\n }\n\n LiveRequestQueue liveRequestQueue = new LiveRequestQueue();\n wsSession.getAttributes().put(LIVE_REQUEST_QUEUE_ATTR, liveRequestQueue);\n\n Runner runner;\n try {\n runner = this.runnerService.getRunner(appName);\n } catch (ResponseStatusException e) {\n log.error(\n \"Failed to get runner for app {} during WebSocket connection: {}\",\n appName,\n e.getMessage());\n wsSession.close(\n CloseStatus.SERVER_ERROR.withReason(\"Runner unavailable: \" + e.getReason()));\n return;\n }\n\n Flowable eventStream = runner.runLive(session, liveRequestQueue, runConfig);\n\n Disposable disposable =\n eventStream\n .subscribeOn(Schedulers.io()) // Offload runner work\n .observeOn(Schedulers.io()) // Send messages on I/O threads\n .subscribe(\n event -> {\n try {\n String jsonEvent = objectMapper.writeValueAsString(event);\n log.debug(\n \"Sending event via WebSocket session {}: {}\",\n wsSession.getId(),\n jsonEvent);\n wsSession.sendMessage(new TextMessage(jsonEvent));\n } catch (JsonProcessingException e) {\n log.error(\n \"Error serializing event to JSON for WebSocket session {}\",\n wsSession.getId(),\n e);\n // Decide if to close session or just log\n } catch (IOException e) {\n log.error(\n \"IOException sending message via WebSocket session {}\",\n wsSession.getId(),\n e);\n // This might mean the session is already closed or problematic\n // Consider closing/disposing here\n try {\n wsSession.close(\n CloseStatus.SERVER_ERROR.withReason(\"Error sending message\"));\n } catch (IOException ignored) {\n }\n }\n },\n error -> {\n log.error(\n \"Error in run_live stream for WebSocket session {}: {}\",\n wsSession.getId(),\n error.getMessage(),\n error);\n String reason =\n error.getMessage() != null ? error.getMessage() : \"Unknown error\";\n try {\n wsSession.close(\n new CloseStatus(\n 1011, // Internal Server Error for WebSocket\n reason.substring(\n 0, Math.min(reason.length(), WEBSOCKET_MAX_BYTES_FOR_REASON))));\n } catch (IOException ignored) {\n }\n },\n () -> {\n log.debug(\n \"run_live stream completed for WebSocket session {}\", wsSession.getId());\n try {\n wsSession.close(CloseStatus.NORMAL);\n } catch (IOException ignored) {\n }\n });\n wsSession.getAttributes().put(LIVE_SUBSCRIPTION_ATTR, disposable);\n log.debug(\"Live run started for WebSocket session {}\", wsSession.getId());\n }\n\n @Override\n protected void handleTextMessage(WebSocketSession wsSession, TextMessage message)\n throws Exception {\n LiveRequestQueue liveRequestQueue =\n (LiveRequestQueue) wsSession.getAttributes().get(LIVE_REQUEST_QUEUE_ATTR);\n\n if (liveRequestQueue == null) {\n log.warn(\n \"Received message on WebSocket session {} but LiveRequestQueue is not available (null).\"\n + \" Message: {}\",\n wsSession.getId(),\n message.getPayload());\n return;\n }\n\n try {\n String payload = message.getPayload();\n log.debug(\"Received text message on WebSocket session {}: {}\", wsSession.getId(), payload);\n\n JsonNode rootNode = objectMapper.readTree(payload);\n LiveRequest.Builder liveRequestBuilder = LiveRequest.builder();\n\n if (rootNode.has(\"content\")) {\n Content content = objectMapper.treeToValue(rootNode.get(\"content\"), Content.class);\n liveRequestBuilder.content(content);\n }\n\n if (rootNode.has(\"blob\")) {\n JsonNode blobNode = rootNode.get(\"blob\");\n Blob.Builder blobBuilder = Blob.builder();\n if (blobNode.has(\"displayName\")) {\n blobBuilder.displayName(blobNode.get(\"displayName\").asText());\n }\n if (blobNode.has(\"data\")) {\n blobBuilder.data(blobNode.get(\"data\").binaryValue());\n }\n // Handle both mime_type and mimeType. Blob states mimeType but we get mime_type from the\n // frontend.\n String mimeType =\n blobNode.has(\"mimeType\")\n ? blobNode.get(\"mimeType\").asText()\n : (blobNode.has(\"mime_type\") ? blobNode.get(\"mime_type\").asText() : null);\n if (mimeType != null) {\n blobBuilder.mimeType(mimeType);\n }\n liveRequestBuilder.blob(blobBuilder.build());\n }\n LiveRequest liveRequest = liveRequestBuilder.build();\n liveRequestQueue.send(liveRequest);\n } catch (JsonProcessingException e) {\n log.error(\n \"Error deserializing LiveRequest from WebSocket message for session {}: {}\",\n wsSession.getId(),\n message.getPayload(),\n e);\n wsSession.sendMessage(\n new TextMessage(\n \"{\\\"error\\\":\\\"Invalid JSON format for LiveRequest\\\", \\\"details\\\":\\\"\"\n + e.getMessage()\n + \"\\\"}\"));\n } catch (Exception e) {\n log.error(\n \"Unexpected error processing text message for WebSocket session {}: {}\",\n wsSession.getId(),\n message.getPayload(),\n e);\n String reason = e.getMessage() != null ? e.getMessage() : \"Error processing message\";\n wsSession.close(\n new CloseStatus(\n 1011,\n reason.substring(0, Math.min(reason.length(), WEBSOCKET_MAX_BYTES_FOR_REASON))));\n }\n }\n\n @Override\n public void handleTransportError(WebSocketSession wsSession, Throwable exception)\n throws Exception {\n log.error(\n \"WebSocket transport error for session {}: {}\",\n wsSession.getId(),\n exception.getMessage(),\n exception);\n // Cleanup resources similar to afterConnectionClosed\n cleanupSession(wsSession);\n if (wsSession.isOpen()) {\n String reason = exception.getMessage() != null ? exception.getMessage() : \"Transport error\";\n wsSession.close(\n CloseStatus.PROTOCOL_ERROR.withReason(\n reason.substring(0, Math.min(reason.length(), WEBSOCKET_MAX_BYTES_FOR_REASON))));\n }\n }\n\n @Override\n public void afterConnectionClosed(WebSocketSession wsSession, CloseStatus status)\n throws Exception {\n log.info(\n \"WebSocket connection closed: {} with status {}\", wsSession.getId(), status.toString());\n cleanupSession(wsSession);\n }\n\n private void cleanupSession(WebSocketSession wsSession) {\n LiveRequestQueue liveRequestQueue =\n (LiveRequestQueue) wsSession.getAttributes().remove(LIVE_REQUEST_QUEUE_ATTR);\n if (liveRequestQueue != null) {\n liveRequestQueue.close(); // Signal end of input to the runner\n log.debug(\"Called close() on LiveRequestQueue for session {}\", wsSession.getId());\n }\n\n Disposable disposable = (Disposable) wsSession.getAttributes().remove(LIVE_SUBSCRIPTION_ATTR);\n if (disposable != null && !disposable.isDisposed()) {\n disposable.dispose();\n }\n log.debug(\"Cleaned up resources for WebSocket session {}\", wsSession.getId());\n }\n }\n\n /**\n * Main entry point for the Spring Boot application.\n *\n * @param args Command line arguments.\n */\n public static void main(String[] args) {\n System.setProperty(\n \"org.apache.tomcat.websocket.DEFAULT_BUFFER_SIZE\", String.valueOf(10 * 1024 * 1024));\n SpringApplication.run(AdkWebServer.class, args);\n log.info(\"AdkWebServer application started successfully.\");\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/models/Gemini.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.models;\n\nimport static com.google.common.base.StandardSystemProperty.JAVA_VERSION;\nimport static com.google.common.collect.ImmutableList.toImmutableList;\n\nimport com.google.adk.Version;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport com.google.genai.Client;\nimport com.google.genai.ResponseStream;\nimport com.google.genai.types.Blob;\nimport com.google.genai.types.Candidate;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.FileData;\nimport com.google.genai.types.FinishReason;\nimport com.google.genai.types.GenerateContentConfig;\nimport com.google.genai.types.GenerateContentResponse;\nimport com.google.genai.types.HttpOptions;\nimport com.google.genai.types.LiveConnectConfig;\nimport com.google.genai.types.Part;\nimport io.reactivex.rxjava3.core.Flowable;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Objects;\nimport java.util.Optional;\nimport java.util.concurrent.CompletableFuture;\nimport java.util.stream.Stream;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * Represents the Gemini Generative AI model.\n *\n *

This class provides methods for interacting with the Gemini model, including standard\n * request-response generation and establishing persistent bidirectional connections.\n */\npublic class Gemini extends BaseLlm {\n\n private static final Logger logger = LoggerFactory.getLogger(Gemini.class);\n private static final ImmutableMap TRACKING_HEADERS;\n\n static {\n String frameworkLabel = \"google-adk/\" + Version.JAVA_ADK_VERSION;\n String languageLabel = \"gl-java/\" + JAVA_VERSION.value();\n String versionHeaderValue = String.format(\"%s %s\", frameworkLabel, languageLabel);\n\n TRACKING_HEADERS =\n ImmutableMap.of(\n \"x-goog-api-client\", versionHeaderValue,\n \"user-agent\", versionHeaderValue);\n }\n\n private final Client apiClient;\n\n private static final String CONTINUE_OUTPUT_MESSAGE =\n \"Continue output. DO NOT look at this line. ONLY look at the content before this line and\"\n + \" system instruction.\";\n\n /**\n * Constructs a new Gemini instance.\n *\n * @param modelName The name of the Gemini model to use (e.g., \"gemini-2.0-flash\").\n * @param apiClient The genai {@link com.google.genai.Client} instance for making API calls.\n */\n public Gemini(String modelName, Client apiClient) {\n super(modelName);\n this.apiClient = Objects.requireNonNull(apiClient, \"apiClient cannot be null\");\n }\n\n /**\n * Constructs a new Gemini instance with a Google Gemini API key.\n *\n * @param modelName The name of the Gemini model to use (e.g., \"gemini-2.0-flash\").\n * @param apiKey The Google Gemini API key.\n */\n public Gemini(String modelName, String apiKey) {\n super(modelName);\n Objects.requireNonNull(apiKey, \"apiKey cannot be null\");\n this.apiClient =\n Client.builder()\n .apiKey(apiKey)\n .httpOptions(HttpOptions.builder().headers(TRACKING_HEADERS).build())\n .build();\n }\n\n /**\n * Constructs a new Gemini instance with a Google Gemini API key.\n *\n * @param modelName The name of the Gemini model to use (e.g., \"gemini-2.0-flash\").\n * @param vertexCredentials The Vertex AI credentials to access the Gemini model.\n */\n public Gemini(String modelName, VertexCredentials vertexCredentials) {\n super(modelName);\n Objects.requireNonNull(vertexCredentials, \"vertexCredentials cannot be null\");\n Client.Builder apiClientBuilder =\n Client.builder().httpOptions(HttpOptions.builder().headers(TRACKING_HEADERS).build());\n vertexCredentials.project().ifPresent(apiClientBuilder::project);\n vertexCredentials.location().ifPresent(apiClientBuilder::location);\n vertexCredentials.credentials().ifPresent(apiClientBuilder::credentials);\n this.apiClient = apiClientBuilder.build();\n }\n\n /**\n * Returns a new Builder instance for constructing Gemini objects. Note that when building a\n * Gemini object, at least one of apiKey, vertexCredentials, or an explicit apiClient must be set.\n * If multiple are set, the explicit apiClient will take precedence.\n *\n * @return A new {@link Builder}.\n */\n public static Builder builder() {\n return new Builder();\n }\n\n /** Builder for {@link Gemini}. */\n public static class Builder {\n private String modelName;\n private Client apiClient;\n private String apiKey;\n private VertexCredentials vertexCredentials;\n\n private Builder() {}\n\n /**\n * Sets the name of the Gemini model to use.\n *\n * @param modelName The model name (e.g., \"gemini-2.0-flash\").\n * @return This builder.\n */\n @CanIgnoreReturnValue\n public Builder modelName(String modelName) {\n this.modelName = modelName;\n return this;\n }\n\n /**\n * Sets the explicit {@link com.google.genai.Client} instance for making API calls. If this is\n * set, apiKey and vertexCredentials will be ignored.\n *\n * @param apiClient The client instance.\n * @return This builder.\n */\n @CanIgnoreReturnValue\n public Builder apiClient(Client apiClient) {\n this.apiClient = apiClient;\n return this;\n }\n\n /**\n * Sets the Google Gemini API key. If {@link #apiClient(Client)} is also set, the explicit\n * client will take precedence. If {@link #vertexCredentials(VertexCredentials)} is also set,\n * this apiKey will take precedence.\n *\n * @param apiKey The API key.\n * @return This builder.\n */\n @CanIgnoreReturnValue\n public Builder apiKey(String apiKey) {\n this.apiKey = apiKey;\n return this;\n }\n\n /**\n * Sets the Vertex AI credentials. If {@link #apiClient(Client)} or {@link #apiKey(String)} are\n * also set, they will take precedence over these credentials.\n *\n * @param vertexCredentials The Vertex AI credentials.\n * @return This builder.\n */\n @CanIgnoreReturnValue\n public Builder vertexCredentials(VertexCredentials vertexCredentials) {\n this.vertexCredentials = vertexCredentials;\n return this;\n }\n\n /**\n * Builds the {@link Gemini} instance.\n *\n * @return A new {@link Gemini} instance.\n * @throws NullPointerException if modelName is null.\n */\n public Gemini build() {\n Objects.requireNonNull(modelName, \"modelName must be set.\");\n\n if (apiClient != null) {\n return new Gemini(modelName, apiClient);\n } else if (apiKey != null) {\n return new Gemini(modelName, apiKey);\n } else if (vertexCredentials != null) {\n return new Gemini(modelName, vertexCredentials);\n } else {\n return new Gemini(\n modelName,\n Client.builder()\n .httpOptions(HttpOptions.builder().headers(TRACKING_HEADERS).build())\n .build());\n }\n }\n }\n\n /**\n * Sanitizes the request to ensure it is compatible with the configured API backend. Required as\n * there are some parameters that if included in the request will raise a runtime error if sent to\n * the wrong backend (e.g. image names when the backend isn't Vertex AI).\n *\n * @param llmRequest The request to sanitize.\n * @return The sanitized request.\n */\n private LlmRequest sanitizeRequest(LlmRequest llmRequest) {\n if (apiClient.vertexAI()) {\n return llmRequest;\n }\n LlmRequest.Builder requestBuilder = llmRequest.toBuilder();\n\n // Using API key from Google AI Studio to call model doesn't support labels.\n llmRequest\n .config()\n .ifPresent(\n config -> {\n if (config.labels().isPresent()) {\n requestBuilder.config(config.toBuilder().labels(null).build());\n }\n });\n\n if (llmRequest.contents().isEmpty()) {\n return requestBuilder.build();\n }\n\n // This backend does not support the display_name parameter for file uploads,\n // so it must be removed to prevent request failures.\n ImmutableList updatedContents =\n llmRequest.contents().stream()\n .map(\n content -> {\n if (content.parts().isEmpty() || content.parts().get().isEmpty()) {\n return content;\n }\n\n ImmutableList updatedParts =\n content.parts().get().stream()\n .map(\n part -> {\n Part.Builder partBuilder = part.toBuilder();\n if (part.inlineData().flatMap(Blob::displayName).isPresent()) {\n Blob blob = part.inlineData().get();\n Blob.Builder newBlobBuilder = Blob.builder();\n blob.data().ifPresent(newBlobBuilder::data);\n blob.mimeType().ifPresent(newBlobBuilder::mimeType);\n partBuilder.inlineData(newBlobBuilder.build());\n }\n if (part.fileData().flatMap(FileData::displayName).isPresent()) {\n FileData fileData = part.fileData().get();\n FileData.Builder newFileDataBuilder = FileData.builder();\n fileData.fileUri().ifPresent(newFileDataBuilder::fileUri);\n fileData.mimeType().ifPresent(newFileDataBuilder::mimeType);\n partBuilder.fileData(newFileDataBuilder.build());\n }\n return partBuilder.build();\n })\n .collect(toImmutableList());\n\n return content.toBuilder().parts(updatedParts).build();\n })\n .collect(toImmutableList());\n return requestBuilder.contents(updatedContents).build();\n }\n\n @Override\n public Flowable generateContent(LlmRequest llmRequest, boolean stream) {\n llmRequest = sanitizeRequest(llmRequest);\n List contents = llmRequest.contents();\n // Last content must be from the user, otherwise the model won't respond.\n if (contents.isEmpty() || !Iterables.getLast(contents).role().orElse(\"\").equals(\"user\")) {\n Content userContent = Content.fromParts(Part.fromText(CONTINUE_OUTPUT_MESSAGE));\n contents =\n Stream.concat(contents.stream(), Stream.of(userContent)).collect(toImmutableList());\n }\n\n List finalContents = stripThoughts(contents);\n GenerateContentConfig config = llmRequest.config().orElse(null);\n String effectiveModelName = llmRequest.model().orElse(model());\n\n logger.trace(\"Request Contents: {}\", finalContents);\n logger.trace(\"Request Config: {}\", config);\n\n if (stream) {\n logger.debug(\"Sending streaming generateContent request to model {}\", effectiveModelName);\n CompletableFuture> streamFuture =\n apiClient.async.models.generateContentStream(effectiveModelName, finalContents, config);\n\n return Flowable.defer(\n () -> {\n final StringBuilder accumulatedText = new StringBuilder();\n // Array to bypass final local variable reassignment in lambda.\n final GenerateContentResponse[] lastRawResponseHolder = {null};\n\n return Flowable.fromFuture(streamFuture)\n .flatMapIterable(iterable -> iterable)\n .concatMap(\n rawResponse -> {\n lastRawResponseHolder[0] = rawResponse;\n logger.trace(\"Raw streaming response: {}\", rawResponse);\n\n List responsesToEmit = new ArrayList<>();\n LlmResponse currentProcessedLlmResponse = LlmResponse.create(rawResponse);\n String currentTextChunk = getTextFromLlmResponse(currentProcessedLlmResponse);\n\n if (!currentTextChunk.isEmpty()) {\n accumulatedText.append(currentTextChunk);\n LlmResponse partialResponse =\n currentProcessedLlmResponse.toBuilder().partial(true).build();\n responsesToEmit.add(partialResponse);\n } else {\n if (accumulatedText.length() > 0\n && shouldEmitAccumulatedText(currentProcessedLlmResponse)) {\n LlmResponse aggregatedTextResponse =\n LlmResponse.builder()\n .content(\n Content.builder()\n .parts(\n ImmutableList.of(\n Part.builder()\n .text(accumulatedText.toString())\n .build()))\n .build())\n .build();\n responsesToEmit.add(aggregatedTextResponse);\n accumulatedText.setLength(0);\n }\n responsesToEmit.add(currentProcessedLlmResponse);\n }\n logger.debug(\"Responses to emit: {}\", responsesToEmit);\n return Flowable.fromIterable(responsesToEmit);\n })\n .concatWith(\n Flowable.defer(\n () -> {\n if (accumulatedText.length() > 0 && lastRawResponseHolder[0] != null) {\n GenerateContentResponse finalRawResp = lastRawResponseHolder[0];\n boolean isStop =\n finalRawResp\n .candidates()\n .flatMap(\n candidates ->\n candidates.isEmpty()\n ? Optional.empty()\n : Optional.of(candidates.get(0)))\n .flatMap(Candidate::finishReason)\n .map(\n finishReason ->\n finishReason.equals(\n new FinishReason(FinishReason.Known.STOP)))\n .orElse(false);\n\n if (isStop) {\n LlmResponse finalAggregatedTextResponse =\n LlmResponse.builder()\n .content(\n Content.builder()\n .parts(\n ImmutableList.of(\n Part.builder()\n .text(accumulatedText.toString())\n .build()))\n .build())\n .build();\n return Flowable.just(finalAggregatedTextResponse);\n }\n }\n return Flowable.empty();\n }));\n });\n } else {\n logger.debug(\"Sending generateContent request to model {}\", effectiveModelName);\n return Flowable.fromFuture(\n apiClient\n .async\n .models\n .generateContent(effectiveModelName, finalContents, config)\n .thenApplyAsync(LlmResponse::create));\n }\n }\n\n /**\n * Extracts text content from the first part of an LlmResponse, if available.\n *\n * @param llmResponse The LlmResponse to extract text from.\n * @return The text content, or an empty string if not found.\n */\n private String getTextFromLlmResponse(LlmResponse llmResponse) {\n return llmResponse\n .content()\n .flatMap(Content::parts)\n .filter(parts -> !parts.isEmpty())\n .map(parts -> parts.get(0))\n .flatMap(Part::text)\n .orElse(\"\");\n }\n\n /**\n * Determines if accumulated text should be emitted based on the current LlmResponse. We flush if\n * current response is not a text continuation (e.g., no content, no parts, or the first part is\n * not inline_data, meaning it's something else or just empty, thereby warranting a flush of\n * preceding text).\n *\n * @param currentLlmResponse The current LlmResponse being processed.\n * @return True if accumulated text should be emitted, false otherwise.\n */\n private boolean shouldEmitAccumulatedText(LlmResponse currentLlmResponse) {\n Optional contentOpt = currentLlmResponse.content();\n if (contentOpt.isEmpty()) {\n return true;\n }\n\n Optional> partsOpt = contentOpt.get().parts();\n if (partsOpt.isEmpty() || partsOpt.get().isEmpty()) {\n return true;\n }\n\n // If content and parts are present, and parts list is not empty, we want to yield accumulated\n // text only if `text` is present AND (`not llm_response.content` OR `not\n // llm_response.content.parts` OR `not llm_response.content.parts[0].inline_data`)\n // This means we flush if the first part does NOT have inline_data.\n // If it *has* inline_data, the condition below is false,\n // and we would not flush based on this specific sub-condition.\n Part firstPart = partsOpt.get().get(0);\n return firstPart.inlineData().isEmpty();\n }\n\n @Override\n public BaseLlmConnection connect(LlmRequest llmRequest) {\n llmRequest = sanitizeRequest(llmRequest);\n logger.debug(\"Establishing Gemini connection.\");\n LiveConnectConfig liveConnectConfig = llmRequest.liveConnectConfig();\n String effectiveModelName = llmRequest.model().orElse(model());\n\n logger.debug(\"Connecting to model {}\", effectiveModelName);\n logger.trace(\"Connection Config: {}\", liveConnectConfig);\n\n return new GeminiLlmConnection(apiClient, effectiveModelName, liveConnectConfig);\n }\n\n /** Removes any `Part` that contains only a `thought` from the content list. */\n private List stripThoughts(List originalContents) {\n List updatedContents = new ArrayList<>();\n for (Content content : originalContents) {\n ImmutableList nonThoughtParts =\n content.parts().orElse(ImmutableList.of()).stream()\n // Keep if thought is not present OR if thought is present but false\n .filter(part -> part.thought().map(isThought -> !isThought).orElse(true))\n .collect(toImmutableList());\n updatedContents.add(content.toBuilder().parts(nonThoughtParts).build());\n }\n return updatedContents;\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/runner/Runner.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.runner;\n\nimport com.google.adk.Telemetry;\nimport com.google.adk.agents.BaseAgent;\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.agents.LiveRequestQueue;\nimport com.google.adk.agents.LlmAgent;\nimport com.google.adk.agents.RunConfig;\nimport com.google.adk.artifacts.BaseArtifactService;\nimport com.google.adk.events.Event;\nimport com.google.adk.sessions.BaseSessionService;\nimport com.google.adk.sessions.Session;\nimport com.google.adk.utils.CollectionUtils;\nimport com.google.common.collect.ImmutableList;\nimport com.google.genai.types.AudioTranscriptionConfig;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.Modality;\nimport com.google.genai.types.Part;\nimport io.opentelemetry.api.trace.Span;\nimport io.opentelemetry.api.trace.StatusCode;\nimport io.opentelemetry.context.Scope;\nimport io.reactivex.rxjava3.core.Flowable;\nimport io.reactivex.rxjava3.core.Maybe;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Optional;\n\n/** The main class for the GenAI Agents runner. */\npublic class Runner {\n private final BaseAgent agent;\n private final String appName;\n private final BaseArtifactService artifactService;\n private final BaseSessionService sessionService;\n\n /** Creates a new {@code Runner}. */\n public Runner(\n BaseAgent agent,\n String appName,\n BaseArtifactService artifactService,\n BaseSessionService sessionService) {\n this.agent = agent;\n this.appName = appName;\n this.artifactService = artifactService;\n this.sessionService = sessionService;\n }\n\n public BaseAgent agent() {\n return this.agent;\n }\n\n public String appName() {\n return this.appName;\n }\n\n public BaseArtifactService artifactService() {\n return this.artifactService;\n }\n\n public BaseSessionService sessionService() {\n return this.sessionService;\n }\n\n /**\n * Appends a new user message to the session history.\n *\n * @throws IllegalArgumentException if message has no parts.\n */\n private void appendNewMessageToSession(\n Session session,\n Content newMessage,\n InvocationContext invocationContext,\n boolean saveInputBlobsAsArtifacts) {\n if (newMessage.parts().isEmpty()) {\n throw new IllegalArgumentException(\"No parts in the new_message.\");\n }\n\n if (this.artifactService != null && saveInputBlobsAsArtifacts) {\n // The runner directly saves the artifacts (if applicable) in the\n // user message and replaces the artifact data with a file name\n // placeholder.\n for (int i = 0; i < newMessage.parts().get().size(); i++) {\n Part part = newMessage.parts().get().get(i);\n if (part.inlineData().isEmpty()) {\n continue;\n }\n String fileName = \"artifact_\" + invocationContext.invocationId() + \"_\" + i;\n var unused =\n this.artifactService.saveArtifact(\n this.appName, session.userId(), session.id(), fileName, part);\n\n newMessage\n .parts()\n .get()\n .set(\n i,\n Part.fromText(\n \"Uploaded file: \" + fileName + \". It has been saved to the artifacts\"));\n }\n }\n // Appends only. We do not yield the event because it's not from the model.\n Event event =\n Event.builder()\n .id(Event.generateEventId())\n .invocationId(invocationContext.invocationId())\n .author(\"user\")\n .content(Optional.of(newMessage))\n .build();\n this.sessionService.appendEvent(session, event);\n }\n\n /**\n * Runs the agent in the standard mode.\n *\n * @param userId The ID of the user for the session.\n * @param sessionId The ID of the session to run the agent in.\n * @param newMessage The new message from the user to process.\n * @param runConfig Configuration for the agent run.\n * @return A Flowable stream of {@link Event} objects generated by the agent during execution.\n */\n public Flowable runAsync(\n String userId, String sessionId, Content newMessage, RunConfig runConfig) {\n Maybe maybeSession =\n this.sessionService.getSession(appName, userId, sessionId, Optional.empty());\n return maybeSession\n .switchIfEmpty(\n Single.error(\n new IllegalArgumentException(\n String.format(\"Session not found: %s for user %s\", sessionId, userId))))\n .flatMapPublisher(session -> this.runAsync(session, newMessage, runConfig));\n }\n\n /**\n * Asynchronously runs the agent for a given user and session, processing a new message and using\n * a default {@link RunConfig}.\n *\n *

This method initiates an agent execution within the specified session, appending the\n * provided new message to the session's history. It utilizes a default {@code RunConfig} to\n * control execution parameters. The method returns a stream of {@link Event} objects representing\n * the agent's activity during the run.\n *\n * @param userId The ID of the user initiating the session.\n * @param sessionId The ID of the session in which the agent will run.\n * @param newMessage The new {@link Content} message to be processed by the agent.\n * @return A {@link Flowable} emitting {@link Event} objects generated by the agent.\n */\n public Flowable runAsync(String userId, String sessionId, Content newMessage) {\n return runAsync(userId, sessionId, newMessage, RunConfig.builder().build());\n }\n\n /**\n * Runs the agent in the standard mode using a provided Session object.\n *\n * @param session The session to run the agent in.\n * @param newMessage The new message from the user to process.\n * @param runConfig Configuration for the agent run.\n * @return A Flowable stream of {@link Event} objects generated by the agent during execution.\n */\n public Flowable runAsync(Session session, Content newMessage, RunConfig runConfig) {\n Span span = Telemetry.getTracer().spanBuilder(\"invocation\").startSpan();\n try (Scope scope = span.makeCurrent()) {\n return Flowable.just(session)\n .flatMap(\n sess -> {\n BaseAgent rootAgent = this.agent;\n InvocationContext invocationContext =\n InvocationContext.create(\n this.sessionService,\n this.artifactService,\n InvocationContext.newInvocationContextId(),\n rootAgent,\n sess,\n newMessage,\n runConfig);\n\n if (newMessage != null) {\n appendNewMessageToSession(\n sess, newMessage, invocationContext, runConfig.saveInputBlobsAsArtifacts());\n }\n\n invocationContext.agent(this.findAgentToRun(sess, rootAgent));\n Flowable events = invocationContext.agent().runAsync(invocationContext);\n return events.doOnNext(event -> this.sessionService.appendEvent(sess, event));\n })\n .doOnError(\n throwable -> {\n span.setStatus(StatusCode.ERROR, \"Error in runAsync Flowable execution\");\n span.recordException(throwable);\n })\n .doFinally(span::end);\n } catch (Throwable t) {\n span.setStatus(StatusCode.ERROR, \"Error during runAsync synchronous setup\");\n span.recordException(t);\n span.end();\n return Flowable.error(t);\n }\n }\n\n /**\n * Creates an {@link InvocationContext} for a live (streaming) run.\n *\n * @return invocation context configured for a live run.\n */\n private InvocationContext newInvocationContextForLive(\n Session session, Optional liveRequestQueue, RunConfig runConfig) {\n RunConfig.Builder runConfigBuilder = RunConfig.builder(runConfig);\n if (!CollectionUtils.isNullOrEmpty(runConfig.responseModalities())\n && liveRequestQueue.isPresent()) {\n // Default to AUDIO modality if not specified.\n if (CollectionUtils.isNullOrEmpty(runConfig.responseModalities())) {\n runConfigBuilder.setResponseModalities(\n ImmutableList.of(new Modality(Modality.Known.AUDIO)));\n if (runConfig.outputAudioTranscription() == null) {\n runConfigBuilder.setOutputAudioTranscription(AudioTranscriptionConfig.builder().build());\n }\n } else if (!runConfig.responseModalities().contains(new Modality(Modality.Known.TEXT))) {\n if (runConfig.outputAudioTranscription() == null) {\n runConfigBuilder.setOutputAudioTranscription(AudioTranscriptionConfig.builder().build());\n }\n }\n }\n return newInvocationContext(session, liveRequestQueue, runConfigBuilder.build());\n }\n\n /**\n * Creates an {@link InvocationContext} for the given session, request queue, and config.\n *\n * @return a new {@link InvocationContext}.\n */\n private InvocationContext newInvocationContext(\n Session session, Optional liveRequestQueue, RunConfig runConfig) {\n BaseAgent rootAgent = this.agent;\n InvocationContext invocationContext =\n InvocationContext.create(\n this.sessionService,\n this.artifactService,\n rootAgent,\n session,\n liveRequestQueue.orElse(null),\n runConfig);\n invocationContext.agent(this.findAgentToRun(session, rootAgent));\n return invocationContext;\n }\n\n /**\n * Runs the agent in live mode, appending generated events to the session.\n *\n * @return stream of events from the agent.\n */\n public Flowable runLive(\n Session session, LiveRequestQueue liveRequestQueue, RunConfig runConfig) {\n Span span = Telemetry.getTracer().spanBuilder(\"invocation\").startSpan();\n try (Scope scope = span.makeCurrent()) {\n InvocationContext invocationContext =\n newInvocationContextForLive(session, Optional.of(liveRequestQueue), runConfig);\n return invocationContext\n .agent()\n .runLive(invocationContext)\n .doOnNext(event -> this.sessionService.appendEvent(session, event))\n .doOnError(\n throwable -> {\n span.setStatus(StatusCode.ERROR, \"Error in runLive Flowable execution\");\n span.recordException(throwable);\n })\n .doFinally(span::end);\n } catch (Throwable t) {\n span.setStatus(StatusCode.ERROR, \"Error during runLive synchronous setup\");\n span.recordException(t);\n span.end();\n return Flowable.error(t);\n }\n }\n\n /**\n * Retrieves the session and runs the agent in live mode.\n *\n * @return stream of events from the agent.\n * @throws IllegalArgumentException if the session is not found.\n */\n public Flowable runLive(\n String userId, String sessionId, LiveRequestQueue liveRequestQueue, RunConfig runConfig) {\n return this.sessionService\n .getSession(appName, userId, sessionId, Optional.empty())\n .flatMapPublisher(\n session -> {\n if (session == null) {\n return Flowable.error(\n new IllegalArgumentException(\n String.format(\"Session not found: %s for user %s\", sessionId, userId)));\n }\n return this.runLive(session, liveRequestQueue, runConfig);\n });\n }\n\n /**\n * Runs the agent asynchronously with a default user ID.\n *\n * @return stream of generated events.\n */\n public Flowable runWithSessionId(\n String sessionId, Content newMessage, RunConfig runConfig) {\n // TODO(b/410859954): Add user_id to getter or method signature. Assuming \"tmp-user\" for now.\n return this.runAsync(\"tmp-user\", sessionId, newMessage, runConfig);\n }\n\n /**\n * Checks if the agent and its parent chain allow transfer up the tree.\n *\n * @return true if transferable, false otherwise.\n */\n private boolean isTransferableAcrossAgentTree(BaseAgent agentToRun) {\n BaseAgent current = agentToRun;\n while (current != null) {\n // Agents eligible to transfer must have an LLM-based agent parent.\n if (!(current instanceof LlmAgent)) {\n return false;\n }\n // If any agent can't transfer to its parent, the chain is broken.\n LlmAgent agent = (LlmAgent) current;\n if (agent.disallowTransferToParent()) {\n return false;\n }\n current = current.parentAgent();\n }\n return true;\n }\n\n /**\n * Returns the agent that should handle the next request based on session history.\n *\n * @return agent to run.\n */\n private BaseAgent findAgentToRun(Session session, BaseAgent rootAgent) {\n List events = new ArrayList<>(session.events());\n Collections.reverse(events);\n\n for (Event event : events) {\n String author = event.author();\n if (author.equals(\"user\")) {\n continue;\n }\n\n if (author.equals(rootAgent.name())) {\n return rootAgent;\n }\n\n BaseAgent agent = rootAgent.findSubAgent(author);\n\n if (agent == null) {\n continue;\n }\n\n if (this.isTransferableAcrossAgentTree(agent)) {\n return agent;\n }\n }\n\n return rootAgent;\n }\n\n // TODO: run statelessly\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/llmflows/Basic.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows.llmflows;\n\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.agents.LlmAgent;\nimport com.google.adk.models.LlmRequest;\nimport com.google.common.collect.ImmutableList;\nimport com.google.genai.types.GenerateContentConfig;\nimport com.google.genai.types.LiveConnectConfig;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.Optional;\n\n/** {@link RequestProcessor} that handles basic information to build the LLM request. */\npublic final class Basic implements RequestProcessor {\n\n public Basic() {}\n\n @Override\n public Single processRequest(\n InvocationContext context, LlmRequest request) {\n if (!(context.agent() instanceof LlmAgent)) {\n throw new IllegalArgumentException(\"Agent in InvocationContext is not an instance of Agent.\");\n }\n LlmAgent agent = (LlmAgent) context.agent();\n String modelName =\n agent.resolvedModel().model().isPresent()\n ? agent.resolvedModel().model().get().model()\n : agent.resolvedModel().modelName().get();\n\n LiveConnectConfig.Builder liveConnectConfigBuilder =\n LiveConnectConfig.builder().responseModalities(context.runConfig().responseModalities());\n Optional.ofNullable(context.runConfig().speechConfig())\n .ifPresent(liveConnectConfigBuilder::speechConfig);\n Optional.ofNullable(context.runConfig().outputAudioTranscription())\n .ifPresent(liveConnectConfigBuilder::outputAudioTranscription);\n\n LlmRequest.Builder builder =\n request.toBuilder()\n .model(modelName)\n .config(agent.generateContentConfig().orElse(GenerateContentConfig.builder().build()))\n .liveConnectConfig(liveConnectConfigBuilder.build());\n\n agent.outputSchema().ifPresent(builder::outputSchema);\n return Single.just(\n RequestProcessor.RequestProcessingResult.create(builder.build(), ImmutableList.of()));\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/memory/InMemoryMemoryService.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.memory;\n\nimport static com.google.common.collect.ImmutableList.toImmutableList;\n\nimport com.google.adk.events.Event;\nimport com.google.adk.sessions.Session;\nimport com.google.common.base.Strings;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.genai.types.Part;\nimport io.reactivex.rxjava3.core.Completable;\nimport io.reactivex.rxjava3.core.Single;\nimport java.time.Instant;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\n/**\n * An in-memory memory service for prototyping purposes only.\n *\n *

Uses keyword matching instead of semantic search.\n */\npublic final class InMemoryMemoryService implements BaseMemoryService {\n\n // Pattern to extract words, matching the Python version.\n private static final Pattern WORD_PATTERN = Pattern.compile(\"[A-Za-z]+\");\n\n /** Keys are \"app_name/user_id\", values are maps of \"session_id\" to a list of events. */\n private final Map>> sessionEvents;\n\n public InMemoryMemoryService() {\n this.sessionEvents = new ConcurrentHashMap<>();\n }\n\n private static String userKey(String appName, String userId) {\n return appName + \"/\" + userId;\n }\n\n @Override\n public Completable addSessionToMemory(Session session) {\n return Completable.fromAction(\n () -> {\n String key = userKey(session.appName(), session.userId());\n Map> userSessions =\n sessionEvents.computeIfAbsent(key, k -> new ConcurrentHashMap<>());\n ImmutableList nonEmptyEvents =\n session.events().stream()\n .filter(\n event ->\n event.content().isPresent()\n && event.content().get().parts().isPresent()\n && !event.content().get().parts().get().isEmpty())\n .collect(toImmutableList());\n userSessions.put(session.id(), nonEmptyEvents);\n });\n }\n\n @Override\n public Single searchMemory(String appName, String userId, String query) {\n return Single.fromCallable(\n () -> {\n String key = userKey(appName, userId);\n\n if (!sessionEvents.containsKey(key)) {\n return SearchMemoryResponse.builder().build();\n }\n\n Map> userSessions = sessionEvents.get(key);\n\n ImmutableSet wordsInQuery =\n ImmutableSet.copyOf(query.toLowerCase(Locale.ROOT).split(\"\\\\s+\"));\n\n List matchingMemories = new ArrayList<>();\n\n for (List eventsInSession : userSessions.values()) {\n for (Event event : eventsInSession) {\n if (event.content().isEmpty() || event.content().get().parts().isEmpty()) {\n continue;\n }\n\n Set wordsInEvent = new HashSet<>();\n for (Part part : event.content().get().parts().get()) {\n if (!Strings.isNullOrEmpty(part.text().get())) {\n Matcher matcher = WORD_PATTERN.matcher(part.text().get());\n while (matcher.find()) {\n wordsInEvent.add(matcher.group().toLowerCase(Locale.ROOT));\n }\n }\n }\n\n if (wordsInEvent.isEmpty()) {\n continue;\n }\n\n if (!Collections.disjoint(wordsInQuery, wordsInEvent)) {\n MemoryEntry memory =\n MemoryEntry.builder()\n .setContent(event.content().get())\n .setAuthor(event.author())\n .setTimestamp(formatTimestamp(event.timestamp()))\n .build();\n matchingMemories.add(memory);\n }\n }\n }\n\n return SearchMemoryResponse.builder()\n .setMemories(ImmutableList.copyOf(matchingMemories))\n .build();\n });\n }\n\n private String formatTimestamp(long timestamp) {\n return Instant.ofEpochSecond(timestamp).toString();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/sessions/HttpApiClient.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\nimport com.google.auth.oauth2.GoogleCredentials;\nimport com.google.common.base.Ascii;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.genai.errors.GenAiIOException;\nimport com.google.genai.types.HttpOptions;\nimport java.io.IOException;\nimport java.util.Map;\nimport java.util.Optional;\nimport okhttp3.MediaType;\nimport okhttp3.Request;\nimport okhttp3.RequestBody;\nimport okhttp3.Response;\n\n/** Base client for the HTTP APIs. */\npublic class HttpApiClient extends ApiClient {\n public static final MediaType MEDIA_TYPE_APPLICATION_JSON =\n MediaType.parse(\"application/json; charset=utf-8\");\n\n /** Constructs an ApiClient for Google AI APIs. */\n HttpApiClient(Optional apiKey, Optional httpOptions) {\n super(apiKey, httpOptions);\n }\n\n /** Constructs an ApiClient for Vertex AI APIs. */\n HttpApiClient(\n Optional project,\n Optional location,\n Optional credentials,\n Optional httpOptions) {\n super(project, location, credentials, httpOptions);\n }\n\n /** Sends a Http request given the http method, path, and request json string. */\n @Override\n public ApiResponse request(String httpMethod, String path, String requestJson) {\n boolean queryBaseModel =\n Ascii.equalsIgnoreCase(httpMethod, \"GET\") && path.startsWith(\"publishers/google/models/\");\n if (this.vertexAI() && !path.startsWith(\"projects/\") && !queryBaseModel) {\n path =\n String.format(\"projects/%s/locations/%s/\", this.project.get(), this.location.get())\n + path;\n }\n String requestUrl =\n String.format(\n \"%s/%s/%s\", httpOptions.baseUrl().get(), httpOptions.apiVersion().get(), path);\n\n Request.Builder requestBuilder = new Request.Builder().url(requestUrl);\n setHeaders(requestBuilder);\n\n if (Ascii.equalsIgnoreCase(httpMethod, \"POST\")) {\n requestBuilder.post(RequestBody.create(MEDIA_TYPE_APPLICATION_JSON, requestJson));\n\n } else if (Ascii.equalsIgnoreCase(httpMethod, \"GET\")) {\n requestBuilder.get();\n } else if (Ascii.equalsIgnoreCase(httpMethod, \"DELETE\")) {\n requestBuilder.delete();\n } else {\n throw new IllegalArgumentException(\"Unsupported HTTP method: \" + httpMethod);\n }\n return executeRequest(requestBuilder.build());\n }\n\n /** Sets the required headers (including auth) on the request object. */\n private void setHeaders(Request.Builder requestBuilder) {\n for (Map.Entry header :\n httpOptions.headers().orElse(ImmutableMap.of()).entrySet()) {\n requestBuilder.header(header.getKey(), header.getValue());\n }\n\n if (apiKey.isPresent()) {\n requestBuilder.header(\"x-goog-api-key\", apiKey.get());\n } else {\n GoogleCredentials cred =\n credentials.orElseThrow(() -> new IllegalStateException(\"credentials is required\"));\n try {\n cred.refreshIfExpired();\n } catch (IOException e) {\n throw new GenAiIOException(\"Failed to refresh credentials.\", e);\n }\n String accessToken;\n try {\n accessToken = cred.getAccessToken().getTokenValue();\n } catch (NullPointerException e) {\n // For test cases where the access token is not available.\n if (e.getMessage()\n .contains(\n \"because the return value of\"\n + \" \\\"com.google.auth.oauth2.GoogleCredentials.getAccessToken()\\\" is null\")) {\n accessToken = \"\";\n } else {\n throw e;\n }\n }\n requestBuilder.header(\"Authorization\", \"Bearer \" + accessToken);\n\n if (cred.getQuotaProjectId() != null) {\n requestBuilder.header(\"x-goog-user-project\", cred.getQuotaProjectId());\n }\n }\n }\n\n /** Executes the given HTTP request. */\n private ApiResponse executeRequest(Request request) {\n try {\n Response response = httpClient.newCall(request).execute();\n return new HttpApiResponse(response);\n } catch (IOException e) {\n throw new GenAiIOException(\"Failed to execute HTTP request.\", e);\n }\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/llmflows/Contents.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows.llmflows;\n\nimport static com.google.common.collect.ImmutableList.toImmutableList;\n\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.google.adk.JsonBaseModel;\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.agents.LlmAgent;\nimport com.google.adk.events.Event;\nimport com.google.adk.models.LlmRequest;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Iterables;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.FunctionCall;\nimport com.google.genai.types.FunctionResponse;\nimport com.google.genai.types.Part;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.Set;\n\n/** {@link RequestProcessor} that populates content in request for LLM flows. */\npublic final class Contents implements RequestProcessor {\n public Contents() {}\n\n @Override\n public Single processRequest(\n InvocationContext context, LlmRequest request) {\n if (!(context.agent() instanceof LlmAgent)) {\n return Single.just(\n RequestProcessor.RequestProcessingResult.create(request, context.session().events()));\n }\n LlmAgent llmAgent = (LlmAgent) context.agent();\n\n if (llmAgent.includeContents() == LlmAgent.IncludeContents.NONE) {\n return Single.just(\n RequestProcessor.RequestProcessingResult.create(\n request.toBuilder().contents(ImmutableList.of()).build(), ImmutableList.of()));\n }\n\n ImmutableList contents =\n getContents(context.branch(), context.session().events(), context.agent().name());\n\n return Single.just(\n RequestProcessor.RequestProcessingResult.create(\n request.toBuilder().contents(contents).build(), ImmutableList.of()));\n }\n\n private ImmutableList getContents(\n Optional currentBranch, List events, String agentName) {\n List filteredEvents = new ArrayList<>();\n\n // Filter the events, leaving the contents and the function calls and responses from the current\n // agent.\n for (Event event : events) {\n // Skip events without content, or generated neither by user nor by model or has empty text.\n // E.g. events purely for mutating session states.\n if (event.content().isEmpty()) {\n continue;\n }\n var content = event.content().get();\n if (content.role().isEmpty()\n || content.role().get().isEmpty()\n || content.parts().isEmpty()\n || content.parts().get().isEmpty()\n || content.parts().get().get(0).text().map(String::isEmpty).orElse(false)) {\n continue;\n }\n\n if (!isEventBelongsToBranch(currentBranch, event)) {\n continue;\n }\n\n // TODO: Skip auth events.\n\n if (isOtherAgentReply(agentName, event)) {\n filteredEvents.add(convertForeignEvent(event));\n } else {\n filteredEvents.add(event);\n }\n }\n\n List resultEvents = rearrangeEventsForLatestFunctionResponse(filteredEvents);\n resultEvents = rearrangeEventsForAsyncFunctionResponsesInHistory(resultEvents);\n\n return resultEvents.stream()\n .map(Event::content)\n .flatMap(Optional::stream)\n .collect(toImmutableList());\n }\n\n /** Whether the event is a reply from another agent. */\n private static boolean isOtherAgentReply(String agentName, Event event) {\n return !agentName.isEmpty()\n && !event.author().equals(agentName)\n && !event.author().equals(\"user\");\n }\n\n /** Converts an {@code event} authored by another agent to a 'contextual-only' event. */\n private static Event convertForeignEvent(Event event) {\n if (event.content().isEmpty()\n || event.content().get().parts().isEmpty()\n || event.content().get().parts().get().isEmpty()) {\n return event;\n }\n\n List parts = new ArrayList<>();\n parts.add(Part.fromText(\"For context:\"));\n\n String originalAuthor = event.author();\n\n for (Part part : event.content().get().parts().get()) {\n if (part.text().isPresent() && !part.text().get().isEmpty()) {\n parts.add(Part.fromText(String.format(\"[%s] said: %s\", originalAuthor, part.text().get())));\n } else if (part.functionCall().isPresent()) {\n FunctionCall functionCall = part.functionCall().get();\n parts.add(\n Part.fromText(\n String.format(\n \"[%s] called tool `%s` with parameters: %s\",\n originalAuthor,\n functionCall.name().orElse(\"unknown_tool\"),\n functionCall.args().map(Contents::convertMapToJson).orElse(\"{}\"))));\n } else if (part.functionResponse().isPresent()) {\n FunctionResponse functionResponse = part.functionResponse().get();\n parts.add(\n Part.fromText(\n String.format(\n \"[%s] `%s` tool returned result: %s\",\n originalAuthor,\n functionResponse.name().orElse(\"unknown_tool\"),\n functionResponse.response().map(Contents::convertMapToJson).orElse(\"{}\"))));\n } else {\n parts.add(part);\n }\n }\n\n Content content = Content.builder().role(\"user\").parts(parts).build();\n return event.toBuilder().author(\"user\").content(content).build();\n }\n\n private static String convertMapToJson(Map struct) {\n try {\n return JsonBaseModel.getMapper().writeValueAsString(struct);\n } catch (JsonProcessingException e) {\n throw new IllegalStateException(\"Failed to serialize the object to JSON.\", e);\n }\n }\n\n private static boolean isEventBelongsToBranch(Optional invocationBranchOpt, Event event) {\n Optional eventBranchOpt = event.branch();\n\n if (invocationBranchOpt.isEmpty() || invocationBranchOpt.get().isEmpty()) {\n return true;\n }\n if (eventBranchOpt.isEmpty() || eventBranchOpt.get().isEmpty()) {\n return true;\n }\n return invocationBranchOpt.get().startsWith(eventBranchOpt.get());\n }\n\n /**\n * Rearranges the events for the latest function response. If the latest function response is for\n * an async function call, all events between the initial function call and the latest function\n * response will be removed.\n *\n * @param events The list of events.\n * @return A new list of events with the appropriate rearrangement.\n */\n private static List rearrangeEventsForLatestFunctionResponse(List events) {\n // TODO: b/412663475 - Handle parallel function calls within the same event. Currently, this\n // throws an error.\n if (events.isEmpty() || Iterables.getLast(events).functionResponses().isEmpty()) {\n // No need to process if the list is empty or the last event is not a function response\n return events;\n }\n\n Event latestEvent = Iterables.getLast(events);\n // Extract function response IDs from the latest event\n Set functionResponseIds = new HashSet<>();\n latestEvent\n .content()\n .flatMap(Content::parts)\n .ifPresent(\n parts -> {\n for (Part part : parts) {\n part.functionResponse()\n .flatMap(FunctionResponse::id)\n .ifPresent(functionResponseIds::add);\n }\n });\n\n if (functionResponseIds.isEmpty()) {\n return events;\n }\n\n // Check if the second to last event contains the corresponding function call\n if (events.size() >= 2) {\n Event penultimateEvent = events.get(events.size() - 2);\n boolean matchFound =\n penultimateEvent\n .content()\n .flatMap(Content::parts)\n .map(\n parts -> {\n for (Part part : parts) {\n if (part.functionCall()\n .flatMap(FunctionCall::id)\n .map(functionResponseIds::contains)\n .orElse(false)) {\n return true; // Found a matching function call ID\n }\n }\n return false;\n })\n .orElse(false);\n if (matchFound) {\n // The latest function response is already matched with the immediately preceding event\n return events;\n }\n }\n\n // Look for the corresponding function call event by iterating backwards\n int functionCallEventIndex = -1;\n for (int i = events.size() - 3; i >= 0; i--) { // Start from third-to-last\n Event event = events.get(i);\n Optional> partsOptional = event.content().flatMap(Content::parts);\n if (partsOptional.isPresent()) {\n List parts = partsOptional.get();\n for (Part part : parts) {\n Optional callIdOpt = part.functionCall().flatMap(FunctionCall::id);\n if (callIdOpt.isPresent() && functionResponseIds.contains(callIdOpt.get())) {\n functionCallEventIndex = i;\n // Add all function call IDs from this event to the set\n parts.forEach(\n p ->\n p.functionCall().flatMap(FunctionCall::id).ifPresent(functionResponseIds::add));\n break; // Found the matching event\n }\n }\n }\n if (functionCallEventIndex != -1) {\n break; // Exit outer loop once found\n }\n }\n\n if (functionCallEventIndex == -1) {\n if (!functionResponseIds.isEmpty()) {\n throw new IllegalStateException(\n \"No function call event found for function response IDs: \" + functionResponseIds);\n } else {\n return events; // No IDs to match, no rearrangement based on this logic.\n }\n }\n\n List resultEvents = new ArrayList<>(events.subList(0, functionCallEventIndex + 1));\n\n // Collect all function response events between the call and the latest response\n List functionResponseEventsToMerge = new ArrayList<>();\n for (int i = functionCallEventIndex + 1; i < events.size() - 1; i++) {\n Event intermediateEvent = events.get(i);\n boolean hasMatchingResponse =\n intermediateEvent\n .content()\n .flatMap(Content::parts)\n .map(\n parts -> {\n for (Part part : parts) {\n if (part.functionResponse()\n .flatMap(FunctionResponse::id)\n .map(functionResponseIds::contains)\n .orElse(false)) {\n return true;\n }\n }\n return false;\n })\n .orElse(false);\n if (hasMatchingResponse) {\n functionResponseEventsToMerge.add(intermediateEvent);\n }\n }\n functionResponseEventsToMerge.add(latestEvent);\n\n if (!functionResponseEventsToMerge.isEmpty()) {\n resultEvents.add(mergeFunctionResponseEvents(functionResponseEventsToMerge));\n }\n\n return resultEvents;\n }\n\n private static List rearrangeEventsForAsyncFunctionResponsesInHistory(List events) {\n Map functionCallIdToResponseEventIndex = new HashMap<>();\n for (int i = 0; i < events.size(); i++) {\n final int index = i;\n Event event = events.get(index);\n event\n .content()\n .flatMap(Content::parts)\n .ifPresent(\n parts -> {\n for (Part part : parts) {\n part.functionResponse()\n .ifPresent(\n response ->\n response\n .id()\n .ifPresent(\n functionCallId ->\n functionCallIdToResponseEventIndex.put(\n functionCallId, index)));\n }\n });\n }\n\n List resultEvents = new ArrayList<>();\n // Keep track of response events already added to avoid duplicates when merging\n Set processedResponseIndices = new HashSet<>();\n\n for (int i = 0; i < events.size(); i++) {\n Event event = events.get(i);\n\n // Skip response events that have already been processed and added alongside their call event\n if (processedResponseIndices.contains(i)) {\n continue;\n }\n\n Optional> partsOptional = event.content().flatMap(Content::parts);\n boolean hasFunctionCalls =\n partsOptional\n .map(parts -> parts.stream().anyMatch(p -> p.functionCall().isPresent()))\n .orElse(false);\n\n if (hasFunctionCalls) {\n Set responseEventIndices = new HashSet<>();\n // Iterate through parts again to get function call IDs\n partsOptional\n .get()\n .forEach(\n part ->\n part.functionCall()\n .ifPresent(\n call ->\n call.id()\n .ifPresent(\n functionCallId -> {\n if (functionCallIdToResponseEventIndex.containsKey(\n functionCallId)) {\n responseEventIndices.add(\n functionCallIdToResponseEventIndex.get(\n functionCallId));\n }\n })));\n\n resultEvents.add(event); // Add the function call event\n\n if (!responseEventIndices.isEmpty()) {\n List responseEventsToAdd = new ArrayList<>();\n List sortedIndices = new ArrayList<>(responseEventIndices);\n Collections.sort(sortedIndices); // Process in chronological order\n\n for (int index : sortedIndices) {\n if (processedResponseIndices.add(index)) { // Add index and check if it was newly added\n responseEventsToAdd.add(events.get(index));\n }\n }\n\n if (responseEventsToAdd.size() == 1) {\n resultEvents.add(responseEventsToAdd.get(0));\n } else if (responseEventsToAdd.size() > 1) {\n resultEvents.add(mergeFunctionResponseEvents(responseEventsToAdd));\n }\n }\n } else {\n resultEvents.add(event);\n }\n }\n\n return resultEvents;\n }\n\n /**\n * Merges a list of function response events into one event.\n *\n *

The key goal is to ensure: 1. functionCall and functionResponse are always of the same\n * number. 2. The functionCall and functionResponse are consecutively in the content.\n *\n * @param functionResponseEvents A list of function response events. NOTE: functionResponseEvents\n * must fulfill these requirements: 1. The list is in increasing order of timestamp; 2. the\n * first event is the initial function response event; 3. all later events should contain at\n * least one function response part that related to the function call event. Caveat: This\n * implementation doesn't support when a parallel function call event contains async function\n * call of the same name.\n * @return A merged event, that is 1. All later function_response will replace function response\n * part in the initial function response event. 2. All non-function response parts will be\n * appended to the part list of the initial function response event.\n */\n private static Event mergeFunctionResponseEvents(List functionResponseEvents) {\n if (functionResponseEvents.isEmpty()) {\n throw new IllegalArgumentException(\"At least one functionResponse event is required.\");\n }\n if (functionResponseEvents.size() == 1) {\n return functionResponseEvents.get(0);\n }\n\n Event baseEvent = functionResponseEvents.get(0);\n Content baseContent =\n baseEvent\n .content()\n .orElseThrow(() -> new IllegalArgumentException(\"Base event must have content.\"));\n List baseParts =\n baseContent\n .parts()\n .orElseThrow(() -> new IllegalArgumentException(\"Base event content must have parts.\"));\n\n if (baseParts.isEmpty()) {\n throw new IllegalArgumentException(\n \"There should be at least one functionResponse part in the base event.\");\n }\n List partsInMergedEvent = new ArrayList<>(baseParts);\n\n Map partIndicesInMergedEvent = new HashMap<>();\n for (int i = 0; i < partsInMergedEvent.size(); i++) {\n final int index = i;\n Part part = partsInMergedEvent.get(i);\n if (part.functionResponse().isPresent()) {\n part.functionResponse()\n .get()\n .id()\n .ifPresent(functionCallId -> partIndicesInMergedEvent.put(functionCallId, index));\n }\n }\n\n for (Event event : functionResponseEvents.subList(1, functionResponseEvents.size())) {\n if (!hasContentWithNonEmptyParts(event)) {\n continue;\n }\n\n for (Part part : event.content().get().parts().get()) {\n if (part.functionResponse().isPresent()) {\n Optional functionCallIdOpt = part.functionResponse().get().id();\n if (functionCallIdOpt.isPresent()) {\n String functionCallId = functionCallIdOpt.get();\n if (partIndicesInMergedEvent.containsKey(functionCallId)) {\n partsInMergedEvent.set(partIndicesInMergedEvent.get(functionCallId), part);\n } else {\n partsInMergedEvent.add(part);\n partIndicesInMergedEvent.put(functionCallId, partsInMergedEvent.size() - 1);\n }\n } else {\n partsInMergedEvent.add(part);\n }\n } else {\n partsInMergedEvent.add(part);\n }\n }\n }\n\n return baseEvent.toBuilder()\n .content(\n Optional.of(\n Content.builder().role(baseContent.role().get()).parts(partsInMergedEvent).build()))\n .build();\n }\n\n private static boolean hasContentWithNonEmptyParts(Event event) {\n return event\n .content() // Optional\n .flatMap(Content::parts) // Optional>\n .map(list -> !list.isEmpty()) // Optional\n .orElse(false);\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/agents/LoopAgent.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.agents;\n\nimport com.google.adk.events.Event;\nimport com.google.common.collect.ImmutableList;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport io.reactivex.rxjava3.core.Flowable;\nimport java.util.List;\nimport java.util.Optional;\n\n/**\n * An agent that runs its sub-agents sequentially in a loop.\n *\n *

The loop continues until a sub-agent escalates, or until the maximum number of iterations is\n * reached (if specified).\n */\npublic class LoopAgent extends BaseAgent {\n\n private final Optional maxIterations;\n\n /**\n * Constructor for LoopAgent.\n *\n * @param name The agent's name.\n * @param description The agent's description.\n * @param subAgents The list of sub-agents to run in the loop.\n * @param maxIterations Optional termination condition: maximum number of loop iterations.\n * @param beforeAgentCallback Optional callback before the agent runs.\n * @param afterAgentCallback Optional callback after the agent runs.\n */\n private LoopAgent(\n String name,\n String description,\n List subAgents,\n Optional maxIterations,\n List beforeAgentCallback,\n List afterAgentCallback) {\n\n super(name, description, subAgents, beforeAgentCallback, afterAgentCallback);\n this.maxIterations = maxIterations;\n }\n\n /** Builder for {@link LoopAgent}. */\n public static class Builder {\n private String name;\n private String description;\n private List subAgents;\n private Optional maxIterations = Optional.empty();\n private ImmutableList beforeAgentCallback;\n private ImmutableList afterAgentCallback;\n\n @CanIgnoreReturnValue\n public Builder name(String name) {\n this.name = name;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder description(String description) {\n this.description = description;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder subAgents(List subAgents) {\n this.subAgents = subAgents;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder subAgents(BaseAgent... subAgents) {\n this.subAgents = ImmutableList.copyOf(subAgents);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder maxIterations(int maxIterations) {\n this.maxIterations = Optional.of(maxIterations);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder maxIterations(Optional maxIterations) {\n this.maxIterations = maxIterations;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeAgentCallback(Callbacks.BeforeAgentCallback beforeAgentCallback) {\n this.beforeAgentCallback = ImmutableList.of(beforeAgentCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeAgentCallback(\n List beforeAgentCallback) {\n this.beforeAgentCallback = CallbackUtil.getBeforeAgentCallbacks(beforeAgentCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterAgentCallback(Callbacks.AfterAgentCallback afterAgentCallback) {\n this.afterAgentCallback = ImmutableList.of(afterAgentCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterAgentCallback(List afterAgentCallback) {\n this.afterAgentCallback = CallbackUtil.getAfterAgentCallbacks(afterAgentCallback);\n return this;\n }\n\n public LoopAgent build() {\n // TODO(b/410859954): Add validation for required fields like name.\n return new LoopAgent(\n name, description, subAgents, maxIterations, beforeAgentCallback, afterAgentCallback);\n }\n }\n\n public static Builder builder() {\n return new Builder();\n }\n\n @Override\n protected Flowable runAsyncImpl(InvocationContext invocationContext) {\n List subAgents = subAgents();\n if (subAgents == null || subAgents.isEmpty()) {\n return Flowable.empty();\n }\n\n return Flowable.fromIterable(subAgents)\n .concatMap(subAgent -> subAgent.runAsync(invocationContext))\n .repeat(maxIterations.orElse(Integer.MAX_VALUE))\n .takeUntil(LoopAgent::hasEscalateAction);\n }\n\n @Override\n protected Flowable runLiveImpl(InvocationContext invocationContext) {\n return Flowable.error(\n new UnsupportedOperationException(\"runLive is not defined for LoopAgent yet.\"));\n }\n\n private static boolean hasEscalateAction(Event event) {\n return event.actions().escalate().orElse(false);\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/mcp/McpToolset.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools.mcp;\n\nimport static com.google.common.collect.ImmutableList.toImmutableList;\n\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.google.adk.JsonBaseModel;\nimport com.google.adk.agents.ReadonlyContext;\nimport com.google.adk.tools.BaseTool;\nimport com.google.adk.tools.BaseToolset;\nimport io.modelcontextprotocol.client.McpSyncClient;\nimport io.modelcontextprotocol.client.transport.ServerParameters;\nimport io.modelcontextprotocol.spec.McpSchema.ListToolsResult;\nimport io.reactivex.rxjava3.core.Flowable;\nimport java.util.Objects;\nimport java.util.Optional;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * Connects to a MCP Server, and retrieves MCP Tools into ADK Tools.\n *\n *

Attributes:\n *\n *

    \n *
  • {@code connectionParams}: The connection parameters to the MCP server. Can be either {@code\n * ServerParameters} or {@code SseServerParameters}.\n *
  • {@code session}: The MCP session being initialized with the connection.\n *
\n */\npublic class McpToolset implements BaseToolset {\n private static final Logger logger = LoggerFactory.getLogger(McpToolset.class);\n private final McpSessionManager mcpSessionManager;\n private McpSyncClient mcpSession;\n private final ObjectMapper objectMapper;\n private final Optional toolFilter;\n\n private static final int MAX_RETRIES = 3;\n private static final long RETRY_DELAY_MILLIS = 100;\n\n /**\n * Initializes the McpToolset with SSE server parameters.\n *\n * @param connectionParams The SSE connection parameters to the MCP server.\n * @param objectMapper An ObjectMapper instance for parsing schemas.\n * @param toolFilter An Optional containing either a ToolPredicate or a List of tool names.\n */\n public McpToolset(\n SseServerParameters connectionParams,\n ObjectMapper objectMapper,\n Optional toolFilter) {\n Objects.requireNonNull(connectionParams);\n Objects.requireNonNull(objectMapper);\n this.objectMapper = objectMapper;\n this.mcpSessionManager = new McpSessionManager(connectionParams);\n this.toolFilter = toolFilter;\n }\n\n /**\n * Initializes the McpToolset with SSE server parameters and no tool filter.\n *\n * @param connectionParams The SSE connection parameters to the MCP server.\n * @param objectMapper An ObjectMapper instance for parsing schemas.\n */\n public McpToolset(SseServerParameters connectionParams, ObjectMapper objectMapper) {\n this(connectionParams, objectMapper, Optional.empty());\n }\n\n /**\n * Initializes the McpToolset with local server parameters.\n *\n * @param connectionParams The local server connection parameters to the MCP server.\n * @param objectMapper An ObjectMapper instance for parsing schemas.\n * @param toolFilter An Optional containing either a ToolPredicate or a List of tool names.\n */\n public McpToolset(\n ServerParameters connectionParams, ObjectMapper objectMapper, Optional toolFilter) {\n Objects.requireNonNull(connectionParams);\n Objects.requireNonNull(objectMapper);\n this.objectMapper = objectMapper;\n this.mcpSessionManager = new McpSessionManager(connectionParams);\n this.toolFilter = toolFilter;\n }\n\n /**\n * Initializes the McpToolset with local server parameters and no tool filter.\n *\n * @param connectionParams The local server connection parameters to the MCP server.\n * @param objectMapper An ObjectMapper instance for parsing schemas.\n */\n public McpToolset(ServerParameters connectionParams, ObjectMapper objectMapper) {\n this(connectionParams, objectMapper, Optional.empty());\n }\n\n /**\n * Initializes the McpToolset with SSE server parameters, using the ObjectMapper used across the\n * ADK.\n *\n * @param connectionParams The SSE connection parameters to the MCP server.\n * @param toolFilter An Optional containing either a ToolPredicate or a List of tool names.\n */\n public McpToolset(SseServerParameters connectionParams, Optional toolFilter) {\n this(connectionParams, JsonBaseModel.getMapper(), toolFilter);\n }\n\n /**\n * Initializes the McpToolset with SSE server parameters, using the ObjectMapper used across the\n * ADK and no tool filter.\n *\n * @param connectionParams The SSE connection parameters to the MCP server.\n */\n public McpToolset(SseServerParameters connectionParams) {\n this(connectionParams, JsonBaseModel.getMapper(), Optional.empty());\n }\n\n /**\n * Initializes the McpToolset with local server parameters, using the ObjectMapper used across the\n * ADK.\n *\n * @param connectionParams The local server connection parameters to the MCP server.\n * @param toolFilter An Optional containing either a ToolPredicate or a List of tool names.\n */\n public McpToolset(ServerParameters connectionParams, Optional toolFilter) {\n this(connectionParams, JsonBaseModel.getMapper(), toolFilter);\n }\n\n /**\n * Initializes the McpToolset with local server parameters, using the ObjectMapper used across the\n * ADK and no tool filter.\n *\n * @param connectionParams The local server connection parameters to the MCP server.\n */\n public McpToolset(ServerParameters connectionParams) {\n this(connectionParams, JsonBaseModel.getMapper(), Optional.empty());\n }\n\n @Override\n public Flowable getTools(ReadonlyContext readonlyContext) {\n return Flowable.fromCallable(\n () -> {\n for (int i = 0; i < MAX_RETRIES; i++) {\n try {\n if (this.mcpSession == null) {\n logger.info(\"MCP session is null or closed, initializing (attempt {}).\", i + 1);\n this.mcpSession = this.mcpSessionManager.createSession();\n }\n\n ListToolsResult toolsResponse = this.mcpSession.listTools();\n return toolsResponse.tools().stream()\n .map(\n tool ->\n new McpTool(\n tool, this.mcpSession, this.mcpSessionManager, this.objectMapper))\n .filter(\n tool ->\n isToolSelected(\n tool, toolFilter, Optional.ofNullable(readonlyContext)))\n .collect(toImmutableList());\n } catch (IllegalArgumentException e) {\n // This could happen if parameters for tool loading are somehow invalid.\n // This is likely a fatal error and should not be retried.\n logger.error(\"Invalid argument encountered during tool loading.\", e);\n throw new McpToolLoadingException(\n \"Invalid argument encountered during tool loading.\", e);\n } catch (RuntimeException e) { // Catch any other unexpected runtime exceptions\n logger.error(\"Unexpected error during tool loading, retry attempt \" + (i + 1), e);\n if (i < MAX_RETRIES - 1) {\n // For other general exceptions, we might still want to retry if they are\n // potentially transient, or if we don't have more specific handling. But it's\n // better to be specific. For now, we'll treat them as potentially retryable but\n // log\n // them at a higher level.\n try {\n logger.info(\n \"Reinitializing MCP session before next retry for unexpected error.\");\n this.mcpSession = this.mcpSessionManager.createSession();\n Thread.sleep(RETRY_DELAY_MILLIS);\n } catch (InterruptedException ie) {\n Thread.currentThread().interrupt();\n logger.error(\n \"Interrupted during retry delay for loadTools (unexpected error).\", ie);\n throw new McpToolLoadingException(\n \"Interrupted during retry delay (unexpected error)\", ie);\n } catch (RuntimeException reinitE) {\n logger.error(\n \"Failed to reinitialize session during retry (unexpected error).\",\n reinitE);\n throw new McpInitializationException(\n \"Failed to reinitialize session during tool loading retry (unexpected\"\n + \" error).\",\n reinitE);\n }\n } else {\n logger.error(\n \"Failed to load tools after multiple retries due to unexpected error.\", e);\n throw new McpToolLoadingException(\n \"Failed to load tools after multiple retries due to unexpected error.\", e);\n }\n }\n }\n // This line should ideally not be reached if retries are handled correctly or an\n // exception is always thrown.\n throw new IllegalStateException(\"Unexpected state in getTools retry loop\");\n })\n .flatMapIterable(tools -> tools);\n }\n\n @Override\n public void close() {\n if (this.mcpSession != null) {\n try {\n this.mcpSession.close();\n logger.debug(\"MCP session closed successfully.\");\n } catch (RuntimeException e) {\n logger.error(\"Failed to close MCP session\", e);\n // We don't throw an exception here, as closing is a cleanup operation and\n // failing to close shouldn't prevent the program from continuing (or exiting).\n // However, we log the error for debugging purposes.\n } finally {\n this.mcpSession = null;\n }\n }\n }\n\n /** Base exception for all errors originating from {@code McpToolset}. */\n public static class McpToolsetException extends RuntimeException {\n public McpToolsetException(String message, Throwable cause) {\n super(message, cause);\n }\n }\n\n /** Exception thrown when there's an error during MCP session initialization. */\n public static class McpInitializationException extends McpToolsetException {\n public McpInitializationException(String message, Throwable cause) {\n super(message, cause);\n }\n }\n\n /** Exception thrown when there's an error during loading tools from the MCP server. */\n public static class McpToolLoadingException extends McpToolsetException {\n public McpToolLoadingException(String message, Throwable cause) {\n super(message, cause);\n }\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/SchemaUtils.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk;\n\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.google.genai.types.Schema;\nimport com.google.genai.types.Type;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\n/** Utility class for validating schemas. */\npublic final class SchemaUtils {\n\n private SchemaUtils() {} // Private constructor for utility class\n\n /**\n * Matches a value against a schema type.\n *\n * @param value The value to match.\n * @param schema The schema to match against.\n * @param isInput Whether the value is an input or output.\n * @return True if the value matches the schema type, false otherwise.\n * @throws IllegalArgumentException If the schema type is not supported.\n */\n @SuppressWarnings(\"unchecked\") // For tool parameter type casting.\n private static Boolean matchType(Object value, Schema schema, Boolean isInput) {\n // Based on types from https://cloud.google.com/vertex-ai/docs/reference/rest/v1/Schema\n Type.Known type = schema.type().get().knownEnum();\n switch (type) {\n case STRING:\n return value instanceof String;\n case INTEGER:\n return value instanceof Integer;\n case BOOLEAN:\n return value instanceof Boolean;\n case NUMBER:\n return value instanceof Number;\n case ARRAY:\n if (value instanceof List) {\n for (Object element : (List) value) {\n if (!matchType(element, schema.items().get(), isInput)) {\n return false;\n }\n }\n return true;\n }\n return false;\n case OBJECT:\n if (value instanceof Map) {\n validateMapOnSchema((Map) value, schema, isInput);\n return true;\n } else {\n return false;\n }\n case TYPE_UNSPECIFIED:\n throw new IllegalArgumentException(\n \"Unsupported type: \" + type + \" is not a Open API data type.\");\n default:\n // This category includes NULL, which is not supported.\n break;\n }\n return false;\n }\n\n /**\n * Validates a map against a schema.\n *\n * @param args The map to validate.\n * @param schema The schema to validate against.\n * @param isInput Whether the map is an input or output.\n * @throws IllegalArgumentException If the map does not match the schema.\n */\n public static void validateMapOnSchema(Map args, Schema schema, Boolean isInput) {\n Map properties = schema.properties().get();\n for (Entry arg : args.entrySet()) {\n // Check if the argument is in the schema.\n if (!properties.containsKey(arg.getKey())) {\n if (isInput) {\n throw new IllegalArgumentException(\n \"Input arg: \" + arg.getKey() + \" does not match agent input schema: \" + schema);\n } else {\n throw new IllegalArgumentException(\n \"Output arg: \" + arg.getKey() + \" does not match agent output schema: \" + schema);\n }\n }\n // Check if the argument type matches the schema type.\n if (!matchType(arg.getValue(), properties.get(arg.getKey()), isInput)) {\n if (isInput) {\n throw new IllegalArgumentException(\n \"Input arg: \" + arg.getKey() + \" does not match agent input schema: \" + schema);\n } else {\n throw new IllegalArgumentException(\n \"Output arg: \" + arg.getKey() + \" does not match agent output schema: \" + schema);\n }\n }\n }\n // Check if all required arguments are present.\n if (schema.required().isPresent()) {\n for (String required : schema.required().get()) {\n if (!args.containsKey(required)) {\n if (isInput) {\n throw new IllegalArgumentException(\"Input args does not contain required \" + required);\n } else {\n throw new IllegalArgumentException(\"Output args does not contain required \" + required);\n }\n }\n }\n }\n }\n\n /**\n * Validates an output string against a schema.\n *\n * @param output The output string to validate.\n * @param schema The schema to validate against.\n * @return The output map.\n * @throws IllegalArgumentException If the output string does not match the schema.\n * @throws JsonProcessingException If the output string cannot be parsed.\n */\n @SuppressWarnings(\"unchecked\") // For tool parameter type casting.\n public static Map validateOutputSchema(String output, Schema schema)\n throws JsonProcessingException {\n Map outputMap = JsonBaseModel.getMapper().readValue(output, HashMap.class);\n validateMapOnSchema(outputMap, schema, false);\n return outputMap;\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/llmflows/Identity.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows.llmflows;\n\nimport com.google.adk.agents.BaseAgent;\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.models.LlmRequest;\nimport com.google.common.base.Strings;\nimport com.google.common.collect.ImmutableList;\nimport io.reactivex.rxjava3.core.Single;\n\n/** {@link RequestProcessor} that gives the agent identity from the framework */\npublic final class Identity implements RequestProcessor {\n\n public Identity() {}\n\n @Override\n public Single processRequest(\n InvocationContext context, LlmRequest request) {\n BaseAgent agent = context.agent();\n StringBuilder builder =\n new StringBuilder()\n .append(\"You are an agent. Your internal name is \")\n .append(agent.name())\n .append(\".\");\n if (!Strings.isNullOrEmpty(agent.description())) {\n builder.append(\" The description about you is \").append(agent.description());\n }\n return Single.just(\n RequestProcessor.RequestProcessingResult.create(\n request.toBuilder().appendInstructions(ImmutableList.of(builder.toString())).build(),\n ImmutableList.of()));\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/applicationintegrationtoolset/IntegrationClient.java", "package com.google.adk.tools.applicationintegrationtoolset;\n\nimport static com.google.common.base.Strings.isNullOrEmpty;\n\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.fasterxml.jackson.databind.node.ObjectNode;\nimport com.google.adk.tools.applicationintegrationtoolset.IntegrationConnectorTool.HttpExecutor;\nimport com.google.common.base.Preconditions;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport java.io.IOException;\nimport java.net.URI;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.util.Arrays;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.Map;\nimport java.util.Objects;\n\n/**\n * Utility class for interacting with Google Cloud Application Integration.\n *\n *

This class provides methods for retrieving OpenAPI spec for an integration or a connection.\n */\npublic class IntegrationClient {\n String project;\n String location;\n String integration;\n List triggers;\n String connection;\n Map> entityOperations;\n List actions;\n private final HttpExecutor httpExecutor;\n public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();\n\n IntegrationClient(\n String project,\n String location,\n String integration,\n List triggers,\n String connection,\n Map> entityOperations,\n List actions,\n HttpExecutor httpExecutor) {\n this.project = project;\n this.location = location;\n this.integration = integration;\n this.triggers = triggers;\n this.connection = connection;\n this.entityOperations = entityOperations;\n this.actions = actions;\n this.httpExecutor = httpExecutor;\n if (!isNullOrEmpty(connection)) {\n validate();\n }\n }\n\n private void validate() {\n // Check if both are null, throw exception\n\n if (this.entityOperations == null && this.actions == null) {\n throw new IllegalArgumentException(\n \"No entity operations or actions provided. Please provide at least one of them.\");\n }\n\n if (this.entityOperations != null) {\n Preconditions.checkArgument(\n !this.entityOperations.isEmpty(), \"entityOperations map cannot be empty\");\n for (Map.Entry> entry : this.entityOperations.entrySet()) {\n String key = entry.getKey();\n List value = entry.getValue();\n Preconditions.checkArgument(\n key != null && !key.isEmpty(),\n \"Enitity in entityOperations map cannot be null or empty\");\n Preconditions.checkArgument(\n value != null, \"Operations for entity '%s' cannot be null\", key);\n for (String str : value) {\n Preconditions.checkArgument(\n str != null && !str.isEmpty(),\n \"Operation for entity '%s' cannot be null or empty\",\n key);\n }\n }\n }\n\n // Validate actions if it's not null\n if (this.actions != null) {\n Preconditions.checkArgument(!this.actions.isEmpty(), \"Actions list cannot be empty\");\n Preconditions.checkArgument(\n this.actions.stream().allMatch(Objects::nonNull),\n \"Actions list cannot contain null values\");\n Preconditions.checkArgument(\n this.actions.stream().noneMatch(String::isEmpty),\n \"Actions list cannot contain empty strings\");\n }\n }\n\n String generateOpenApiSpec() throws Exception {\n String url =\n String.format(\n \"https://%s-integrations.googleapis.com/v1/projects/%s/locations/%s:generateOpenApiSpec\",\n this.location, this.project, this.location);\n\n String jsonRequestBody =\n OBJECT_MAPPER.writeValueAsString(\n ImmutableMap.of(\n \"apiTriggerResources\",\n ImmutableList.of(\n ImmutableMap.of(\n \"integrationResource\",\n this.integration,\n \"triggerId\",\n Arrays.asList(this.triggers))),\n \"fileFormat\",\n \"JSON\"));\n HttpRequest request =\n HttpRequest.newBuilder()\n .uri(URI.create(url))\n .header(\"Authorization\", \"Bearer \" + httpExecutor.getToken())\n .header(\"Content-Type\", \"application/json\")\n .POST(HttpRequest.BodyPublishers.ofString(jsonRequestBody))\n .build();\n HttpResponse response =\n httpExecutor.send(request, HttpResponse.BodyHandlers.ofString());\n\n if (response.statusCode() < 200 || response.statusCode() >= 300) {\n throw new Exception(\"Error fetching OpenAPI spec. Status: \" + response.statusCode());\n }\n return response.body();\n }\n\n @SuppressWarnings(\"unchecked\")\n ObjectNode getOpenApiSpecForConnection(String toolName, String toolInstructions)\n throws IOException, InterruptedException {\n final String integrationName = \"ExecuteConnection\";\n\n ConnectionsClient connectionsClient = createConnectionsClient();\n\n ImmutableMap baseSpecMap = ConnectionsClient.getConnectorBaseSpec();\n ObjectNode connectorSpec = OBJECT_MAPPER.valueToTree(baseSpecMap);\n\n ObjectNode paths = (ObjectNode) connectorSpec.path(\"paths\");\n ObjectNode schemas = (ObjectNode) connectorSpec.path(\"components\").path(\"schemas\");\n\n if (this.entityOperations != null) {\n for (Map.Entry> entry : this.entityOperations.entrySet()) {\n String entity = entry.getKey();\n List operations = entry.getValue();\n\n ConnectionsClient.EntitySchemaAndOperations schemaInfo;\n try {\n schemaInfo = connectionsClient.getEntitySchemaAndOperations(entity);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n throw new IOException(\"Operation was interrupted while getting entity schema\", e);\n }\n\n Map schemaMap = schemaInfo.schema;\n List supportedOperations = schemaInfo.operations;\n\n if (operations == null || operations.isEmpty()) {\n operations = supportedOperations;\n }\n\n String jsonSchemaAsString = OBJECT_MAPPER.writeValueAsString(schemaMap);\n String entityLower = entity.toLowerCase(Locale.ROOT);\n\n schemas.set(\n \"connectorInputPayload_\" + entityLower,\n OBJECT_MAPPER.valueToTree(connectionsClient.connectorPayload(schemaMap)));\n\n for (String operation : operations) {\n String operationLower = operation.toLowerCase(Locale.ROOT);\n String path =\n String.format(\n \"/v2/projects/%s/locations/%s/integrations/%s:execute?triggerId=api_trigger/%s#%s_%s\",\n this.project,\n this.location,\n integrationName,\n integrationName,\n operationLower,\n entityLower);\n\n switch (operationLower) {\n case \"create\":\n paths.set(\n path,\n OBJECT_MAPPER.valueToTree(\n ConnectionsClient.createOperation(entityLower, toolName, toolInstructions)));\n schemas.set(\n \"create_\" + entityLower + \"_Request\",\n OBJECT_MAPPER.valueToTree(ConnectionsClient.createOperationRequest(entityLower)));\n break;\n case \"update\":\n paths.set(\n path,\n OBJECT_MAPPER.valueToTree(\n ConnectionsClient.updateOperation(entityLower, toolName, toolInstructions)));\n schemas.set(\n \"update_\" + entityLower + \"_Request\",\n OBJECT_MAPPER.valueToTree(ConnectionsClient.updateOperationRequest(entityLower)));\n break;\n case \"delete\":\n paths.set(\n path,\n OBJECT_MAPPER.valueToTree(\n ConnectionsClient.deleteOperation(entityLower, toolName, toolInstructions)));\n schemas.set(\n \"delete_\" + entityLower + \"_Request\",\n OBJECT_MAPPER.valueToTree(ConnectionsClient.deleteOperationRequest()));\n break;\n case \"list\":\n paths.set(\n path,\n OBJECT_MAPPER.valueToTree(\n ConnectionsClient.listOperation(\n entityLower, jsonSchemaAsString, toolName, toolInstructions)));\n schemas.set(\n \"list_\" + entityLower + \"_Request\",\n OBJECT_MAPPER.valueToTree(ConnectionsClient.listOperationRequest()));\n break;\n case \"get\":\n paths.set(\n path,\n OBJECT_MAPPER.valueToTree(\n ConnectionsClient.getOperation(\n entityLower, jsonSchemaAsString, toolName, toolInstructions)));\n schemas.set(\n \"get_\" + entityLower + \"_Request\",\n OBJECT_MAPPER.valueToTree(ConnectionsClient.getOperationRequest()));\n break;\n default:\n throw new IllegalArgumentException(\n \"Invalid operation: \" + operation + \" for entity: \" + entity);\n }\n }\n }\n } else if (this.actions != null) {\n for (String action : this.actions) {\n ObjectNode actionDetails =\n OBJECT_MAPPER.valueToTree(connectionsClient.getActionSchema(action));\n\n JsonNode inputSchemaNode = actionDetails.path(\"inputSchema\");\n JsonNode outputSchemaNode = actionDetails.path(\"outputSchema\");\n\n String actionDisplayName = actionDetails.path(\"displayName\").asText(\"\").replace(\" \", \"\");\n String operation = \"EXECUTE_ACTION\";\n\n Map inputSchemaMap = OBJECT_MAPPER.treeToValue(inputSchemaNode, Map.class);\n Map outputSchemaMap =\n OBJECT_MAPPER.treeToValue(outputSchemaNode, Map.class);\n\n if (Objects.equals(action, \"ExecuteCustomQuery\")) {\n schemas.set(\n actionDisplayName + \"_Request\",\n OBJECT_MAPPER.valueToTree(ConnectionsClient.executeCustomQueryRequest()));\n operation = \"EXECUTE_QUERY\";\n } else {\n schemas.set(\n actionDisplayName + \"_Request\",\n OBJECT_MAPPER.valueToTree(ConnectionsClient.actionRequest(actionDisplayName)));\n schemas.set(\n \"connectorInputPayload_\" + actionDisplayName,\n OBJECT_MAPPER.valueToTree(connectionsClient.connectorPayload(inputSchemaMap)));\n }\n\n schemas.set(\n \"connectorOutputPayload_\" + actionDisplayName,\n OBJECT_MAPPER.valueToTree(connectionsClient.connectorPayload(outputSchemaMap)));\n schemas.set(\n actionDisplayName + \"_Response\",\n OBJECT_MAPPER.valueToTree(ConnectionsClient.actionResponse(actionDisplayName)));\n\n String path =\n String.format(\n \"/v2/projects/%s/locations/%s/integrations/%s:execute?triggerId=api_trigger/%s#%s\",\n this.project, this.location, integrationName, integrationName, action);\n\n paths.set(\n path,\n OBJECT_MAPPER.valueToTree(\n ConnectionsClient.getActionOperation(\n action, operation, actionDisplayName, toolName, toolInstructions)));\n }\n } else {\n throw new IllegalArgumentException(\n \"No entity operations or actions provided. Please provide at least one of them.\");\n }\n return connectorSpec;\n }\n\n String getOperationIdFromPathUrl(String openApiSchemaString, String pathUrl) throws Exception {\n JsonNode topLevelNode = OBJECT_MAPPER.readTree(openApiSchemaString);\n JsonNode specNode = topLevelNode.path(\"openApiSpec\");\n if (specNode.isMissingNode() || !specNode.isTextual()) {\n throw new IllegalArgumentException(\n \"Failed to get OpenApiSpec, please check the project and region for the integration.\");\n }\n JsonNode rootNode = OBJECT_MAPPER.readTree(specNode.asText());\n JsonNode paths = rootNode.path(\"paths\");\n\n Iterator> pathsFields = paths.fields();\n while (pathsFields.hasNext()) {\n Map.Entry pathEntry = pathsFields.next();\n String currentPath = pathEntry.getKey();\n if (!currentPath.equals(pathUrl)) {\n continue;\n }\n JsonNode pathItem = pathEntry.getValue();\n\n Iterator> methods = pathItem.fields();\n while (methods.hasNext()) {\n Map.Entry methodEntry = methods.next();\n JsonNode operationNode = methodEntry.getValue();\n\n if (operationNode.has(\"operationId\")) {\n return operationNode.path(\"operationId\").asText();\n }\n }\n }\n throw new Exception(\"Could not find operationId for pathUrl: \" + pathUrl);\n }\n\n ConnectionsClient createConnectionsClient() {\n return new ConnectionsClient(\n this.project, this.location, this.connection, this.httpExecutor, OBJECT_MAPPER);\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/sessions/InMemorySessionService.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\nimport static java.util.stream.Collectors.toCollection;\n\nimport com.google.adk.events.Event;\nimport com.google.adk.events.EventActions;\nimport com.google.common.collect.ImmutableList;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport io.reactivex.rxjava3.core.Completable;\nimport io.reactivex.rxjava3.core.Maybe;\nimport io.reactivex.rxjava3.core.Single;\nimport java.time.Instant;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.Optional;\nimport java.util.UUID;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentMap;\nimport org.jspecify.annotations.Nullable;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * An in-memory implementation of {@link BaseSessionService} assuming {@link Session} objects are\n * mutable regarding their state map, events list, and last update time.\n *\n *

This implementation stores sessions, user state, and app state directly in memory using\n * concurrent maps for basic thread safety. It is suitable for testing or single-node deployments\n * where persistence is not required.\n *\n *

Note: State merging (app/user state prefixed with {@code _app_} / {@code _user_}) occurs\n * during retrieval operations ({@code getSession}, {@code createSession}).\n */\npublic final class InMemorySessionService implements BaseSessionService {\n\n private static final Logger logger = LoggerFactory.getLogger(InMemorySessionService.class);\n\n // Structure: appName -> userId -> sessionId -> Session\n private final ConcurrentMap>>\n sessions;\n // Structure: appName -> userId -> stateKey -> stateValue\n private final ConcurrentMap>>\n userState;\n // Structure: appName -> stateKey -> stateValue\n private final ConcurrentMap> appState;\n\n /** Creates a new instance of the in-memory session service with empty storage. */\n public InMemorySessionService() {\n this.sessions = new ConcurrentHashMap<>();\n this.userState = new ConcurrentHashMap<>();\n this.appState = new ConcurrentHashMap<>();\n }\n\n @Override\n public Single createSession(\n String appName,\n String userId,\n @Nullable ConcurrentMap state,\n @Nullable String sessionId) {\n Objects.requireNonNull(appName, \"appName cannot be null\");\n Objects.requireNonNull(userId, \"userId cannot be null\");\n\n String resolvedSessionId =\n Optional.ofNullable(sessionId)\n .map(String::trim)\n .filter(s -> !s.isEmpty())\n .orElseGet(() -> UUID.randomUUID().toString());\n\n // Ensure state map and events list are mutable for the new session\n ConcurrentMap initialState =\n (state == null) ? new ConcurrentHashMap<>() : new ConcurrentHashMap<>(state);\n List initialEvents = new ArrayList<>();\n\n // Assuming Session constructor or setters allow setting these mutable collections\n Session newSession =\n Session.builder(resolvedSessionId)\n .appName(appName)\n .userId(userId)\n .state(initialState)\n .events(initialEvents)\n .lastUpdateTime(Instant.now())\n .build();\n\n sessions\n .computeIfAbsent(appName, k -> new ConcurrentHashMap<>())\n .computeIfAbsent(userId, k -> new ConcurrentHashMap<>())\n .put(resolvedSessionId, newSession);\n\n // Create a mutable copy for the return value\n Session returnCopy = copySession(newSession);\n // Merge state into the copy before returning\n return Single.just(mergeWithGlobalState(appName, userId, returnCopy));\n }\n\n @Override\n public Maybe getSession(\n String appName, String userId, String sessionId, Optional configOpt) {\n Objects.requireNonNull(appName, \"appName cannot be null\");\n Objects.requireNonNull(userId, \"userId cannot be null\");\n Objects.requireNonNull(sessionId, \"sessionId cannot be null\");\n Objects.requireNonNull(configOpt, \"configOpt cannot be null\");\n\n Session storedSession =\n sessions\n .getOrDefault(appName, new ConcurrentHashMap<>())\n .getOrDefault(userId, new ConcurrentHashMap<>())\n .get(sessionId);\n\n if (storedSession == null) {\n return Maybe.empty();\n }\n\n Session sessionCopy = copySession(storedSession);\n\n // Apply filtering based on config directly to the mutable list in the copy\n GetSessionConfig config = configOpt.orElse(GetSessionConfig.builder().build());\n List eventsInCopy = sessionCopy.events();\n\n config\n .numRecentEvents()\n .ifPresent(\n num -> {\n if (!eventsInCopy.isEmpty() && num < eventsInCopy.size()) {\n // Keep the last 'num' events by removing older ones\n // Create sublist view (modifications affect original list)\n\n List eventsToRemove = eventsInCopy.subList(0, eventsInCopy.size() - num);\n eventsToRemove.clear(); // Clear the sublist view, modifying eventsInCopy\n }\n });\n\n // Only apply timestamp filter if numRecentEvents was not applied\n if (config.numRecentEvents().isEmpty() && config.afterTimestamp().isPresent()) {\n Instant threshold = config.afterTimestamp().get();\n\n eventsInCopy.removeIf(\n event -> getEventTimestampEpochSeconds(event) < threshold.getEpochSecond());\n }\n\n // Merge state into the potentially filtered copy and return\n return Maybe.just(mergeWithGlobalState(appName, userId, sessionCopy));\n }\n\n // Helper to get event timestamp as epoch seconds\n private long getEventTimestampEpochSeconds(Event event) {\n return event.timestamp() / 1000L;\n }\n\n @Override\n public Single listSessions(String appName, String userId) {\n Objects.requireNonNull(appName, \"appName cannot be null\");\n Objects.requireNonNull(userId, \"userId cannot be null\");\n\n Map userSessionsMap =\n sessions.getOrDefault(appName, new ConcurrentHashMap<>()).get(userId);\n\n if (userSessionsMap == null || userSessionsMap.isEmpty()) {\n return Single.just(ListSessionsResponse.builder().build());\n }\n\n // Create copies with empty events and state for the response\n List sessionCopies =\n userSessionsMap.values().stream()\n .map(this::copySessionMetadata)\n .collect(toCollection(ArrayList::new));\n\n return Single.just(ListSessionsResponse.builder().sessions(sessionCopies).build());\n }\n\n @Override\n public Completable deleteSession(String appName, String userId, String sessionId) {\n Objects.requireNonNull(appName, \"appName cannot be null\");\n Objects.requireNonNull(userId, \"userId cannot be null\");\n Objects.requireNonNull(sessionId, \"sessionId cannot be null\");\n\n ConcurrentMap userSessionsMap =\n sessions.getOrDefault(appName, new ConcurrentHashMap<>()).get(userId);\n\n if (userSessionsMap != null) {\n userSessionsMap.remove(sessionId);\n }\n return Completable.complete();\n }\n\n @Override\n public Single listEvents(String appName, String userId, String sessionId) {\n Objects.requireNonNull(appName, \"appName cannot be null\");\n Objects.requireNonNull(userId, \"userId cannot be null\");\n Objects.requireNonNull(sessionId, \"sessionId cannot be null\");\n\n Session storedSession =\n sessions\n .getOrDefault(appName, new ConcurrentHashMap<>())\n .getOrDefault(userId, new ConcurrentHashMap<>())\n .get(sessionId);\n\n if (storedSession == null) {\n return Single.just(ListEventsResponse.builder().build());\n }\n\n ImmutableList eventsCopy = ImmutableList.copyOf(storedSession.events());\n return Single.just(ListEventsResponse.builder().events(eventsCopy).build());\n }\n\n @CanIgnoreReturnValue\n @Override\n public Single appendEvent(Session session, Event event) {\n Objects.requireNonNull(session, \"session cannot be null\");\n Objects.requireNonNull(event, \"event cannot be null\");\n Objects.requireNonNull(session.appName(), \"session.appName cannot be null\");\n Objects.requireNonNull(session.userId(), \"session.userId cannot be null\");\n Objects.requireNonNull(session.id(), \"session.id cannot be null\");\n\n String appName = session.appName();\n String userId = session.userId();\n String sessionId = session.id();\n\n // --- Update User/App State (Same as before) ---\n EventActions actions = event.actions();\n if (actions != null) {\n Map stateDelta = actions.stateDelta();\n if (stateDelta != null && !stateDelta.isEmpty()) {\n stateDelta.forEach(\n (key, value) -> {\n if (key.startsWith(State.APP_PREFIX)) {\n String appStateKey = key.substring(State.APP_PREFIX.length());\n appState\n .computeIfAbsent(appName, k -> new ConcurrentHashMap<>())\n .put(appStateKey, value);\n } else if (key.startsWith(State.USER_PREFIX)) {\n String userStateKey = key.substring(State.USER_PREFIX.length());\n userState\n .computeIfAbsent(appName, k -> new ConcurrentHashMap<>())\n .computeIfAbsent(userId, k -> new ConcurrentHashMap<>())\n .put(userStateKey, value);\n }\n });\n }\n }\n\n BaseSessionService.super.appendEvent(session, event);\n session.lastUpdateTime(getInstantFromEvent(event));\n\n // --- Update the session stored in this service ---\n sessions\n .getOrDefault(appName, new ConcurrentHashMap<>())\n .getOrDefault(userId, new ConcurrentHashMap<>())\n .put(sessionId, session);\n\n return Single.just(event);\n }\n\n /** Converts an event's timestamp to an Instant. Adapt based on actual Event structure. */\n // TODO: have Event.timestamp() return Instant directly\n private Instant getInstantFromEvent(Event event) {\n double epochSeconds = getEventTimestampEpochSeconds(event);\n long seconds = (long) epochSeconds;\n long nanos = (long) ((epochSeconds % 1.0) * 1_000_000_000L);\n return Instant.ofEpochSecond(seconds, nanos);\n }\n\n /**\n * Creates a shallow copy of the session, but with deep copies of the mutable state map and events\n * list. Assumes Session provides necessary getters and a suitable constructor/setters.\n *\n * @param original The session to copy.\n * @return A new Session instance with copied data, including mutable collections.\n */\n private Session copySession(Session original) {\n return Session.builder(original.id())\n .appName(original.appName())\n .userId(original.userId())\n .state(new ConcurrentHashMap<>(original.state()))\n .events(new ArrayList<>(original.events()))\n .lastUpdateTime(original.lastUpdateTime())\n .build();\n }\n\n /**\n * Creates a copy of the session containing only metadata fields (ID, appName, userId, timestamp).\n * State and Events are explicitly *not* copied.\n *\n * @param original The session whose metadata to copy.\n * @return A new Session instance with only metadata fields populated.\n */\n private Session copySessionMetadata(Session original) {\n return Session.builder(original.id())\n .appName(original.appName())\n .userId(original.userId())\n .lastUpdateTime(original.lastUpdateTime())\n .build();\n }\n\n /**\n * Merges the app-specific and user-specific state into the provided *mutable* session's state\n * map.\n *\n * @param appName The application name.\n * @param userId The user ID.\n * @param session The mutable session whose state map will be augmented.\n * @return The same session instance passed in, now with merged state.\n */\n @CanIgnoreReturnValue\n private Session mergeWithGlobalState(String appName, String userId, Session session) {\n Map sessionState = session.state();\n\n // Merge App State directly into the session's state map\n appState\n .getOrDefault(appName, new ConcurrentHashMap())\n .forEach((key, value) -> sessionState.put(State.APP_PREFIX + key, value));\n\n userState\n .getOrDefault(appName, new ConcurrentHashMap<>())\n .getOrDefault(userId, new ConcurrentHashMap<>())\n .forEach((key, value) -> sessionState.put(State.USER_PREFIX + key, value));\n\n return session;\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/artifacts/GcsArtifactService.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.artifacts;\n\nimport static java.util.Collections.max;\n\nimport com.google.cloud.storage.Blob;\nimport com.google.cloud.storage.BlobId;\nimport com.google.cloud.storage.BlobInfo;\nimport com.google.cloud.storage.Storage;\nimport com.google.cloud.storage.Storage.BlobListOption;\nimport com.google.cloud.storage.StorageException;\nimport com.google.common.base.Splitter;\nimport com.google.common.base.VerifyException;\nimport com.google.common.collect.ImmutableList;\nimport com.google.genai.types.Part;\nimport io.reactivex.rxjava3.core.Completable;\nimport io.reactivex.rxjava3.core.Maybe;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.Set;\n\n/** An artifact service implementation using Google Cloud Storage (GCS). */\npublic final class GcsArtifactService implements BaseArtifactService {\n private final String bucketName;\n private final Storage storageClient;\n\n /**\n * Initializes the GcsArtifactService.\n *\n * @param bucketName The name of the GCS bucket to use.\n * @param storageClient The GCS storage client instance.\n */\n public GcsArtifactService(String bucketName, Storage storageClient) {\n this.bucketName = bucketName;\n this.storageClient = storageClient;\n }\n\n /**\n * Checks if a filename uses the user namespace.\n *\n * @param filename Filename to check.\n * @return true if prefixed with \"user:\", false otherwise.\n */\n private boolean fileHasUserNamespace(String filename) {\n return filename != null && filename.startsWith(\"user:\");\n }\n\n /**\n * Constructs the blob prefix for an artifact (excluding version).\n *\n * @param appName Application name.\n * @param userId User ID.\n * @param sessionId Session ID.\n * @param filename Artifact filename.\n * @return prefix string for blob location.\n */\n private String getBlobPrefix(String appName, String userId, String sessionId, String filename) {\n if (fileHasUserNamespace(filename)) {\n return String.format(\"%s/%s/user/%s/\", appName, userId, filename);\n } else {\n return String.format(\"%s/%s/%s/%s/\", appName, userId, sessionId, filename);\n }\n }\n\n /**\n * Constructs the full blob name for an artifact, including version.\n *\n * @param appName Application name.\n * @param userId User ID.\n * @param sessionId Session ID.\n * @param filename Artifact filename.\n * @param version Artifact version.\n * @return full blob name.\n */\n private String getBlobName(\n String appName, String userId, String sessionId, String filename, int version) {\n return getBlobPrefix(appName, userId, sessionId, filename) + version;\n }\n\n /**\n * Saves an artifact to GCS and assigns a new version.\n *\n * @param appName Application name.\n * @param userId User ID.\n * @param sessionId Session ID.\n * @param filename Artifact filename.\n * @param artifact Artifact content to save.\n * @return Single with assigned version number.\n */\n @Override\n public Single saveArtifact(\n String appName, String userId, String sessionId, String filename, Part artifact) {\n return listVersions(appName, userId, sessionId, filename)\n .map(versions -> versions.isEmpty() ? 0 : max(versions) + 1)\n .map(\n nextVersion -> {\n String blobName = getBlobName(appName, userId, sessionId, filename, nextVersion);\n BlobId blobId = BlobId.of(bucketName, blobName);\n\n BlobInfo blobInfo =\n BlobInfo.newBuilder(blobId)\n .setContentType(artifact.inlineData().get().mimeType().orElse(null))\n .build();\n\n try {\n byte[] dataToSave =\n artifact\n .inlineData()\n .get()\n .data()\n .orElseThrow(\n () ->\n new IllegalArgumentException(\n \"Saveable artifact data must be non-empty.\"));\n storageClient.create(blobInfo, dataToSave);\n return nextVersion;\n } catch (StorageException e) {\n throw new VerifyException(\"Failed to save artifact to GCS\", e);\n }\n });\n }\n\n /**\n * Loads an artifact from GCS.\n *\n * @param appName Application name.\n * @param userId User ID.\n * @param sessionId Session ID.\n * @param filename Artifact filename.\n * @param version Optional version to load. Loads latest if empty.\n * @return Maybe with loaded artifact, or empty if not found.\n */\n @Override\n public Maybe loadArtifact(\n String appName, String userId, String sessionId, String filename, Optional version) {\n return version\n .map(Maybe::just)\n .orElseGet(\n () ->\n listVersions(appName, userId, sessionId, filename)\n .flatMapMaybe(\n versions -> versions.isEmpty() ? Maybe.empty() : Maybe.just(max(versions))))\n .flatMap(\n versionToLoad -> {\n String blobName = getBlobName(appName, userId, sessionId, filename, versionToLoad);\n BlobId blobId = BlobId.of(bucketName, blobName);\n\n try {\n Blob blob = storageClient.get(blobId);\n if (blob == null || !blob.exists()) {\n return Maybe.empty();\n }\n byte[] data = blob.getContent();\n String mimeType = blob.getContentType();\n return Maybe.just(Part.fromBytes(data, mimeType));\n } catch (StorageException e) {\n return Maybe.empty();\n }\n });\n }\n\n /**\n * Lists artifact filenames for a user and session.\n *\n * @param appName Application name.\n * @param userId User ID.\n * @param sessionId Session ID.\n * @return Single with sorted list of artifact filenames.\n */\n @Override\n public Single listArtifactKeys(\n String appName, String userId, String sessionId) {\n Set filenames = new HashSet<>();\n\n // List session-specific files\n String sessionPrefix = String.format(\"%s/%s/%s/\", appName, userId, sessionId);\n try {\n for (Blob blob :\n storageClient.list(bucketName, BlobListOption.prefix(sessionPrefix)).iterateAll()) {\n List parts = Splitter.on('/').splitToList(blob.getName());\n filenames.add(parts.get(3)); // appName/userId/sessionId/filename/version\n }\n } catch (StorageException e) {\n throw new VerifyException(\"Failed to list session artifacts from GCS\", e);\n }\n\n // List user-namespace files\n String userPrefix = String.format(\"%s/%s/user/\", appName, userId);\n try {\n for (Blob blob :\n storageClient.list(bucketName, BlobListOption.prefix(userPrefix)).iterateAll()) {\n List parts = Splitter.on('/').splitToList(blob.getName());\n filenames.add(parts.get(3)); // appName/userId/user/filename/version\n }\n } catch (StorageException e) {\n throw new VerifyException(\"Failed to list user artifacts from GCS\", e);\n }\n\n return Single.just(\n ListArtifactsResponse.builder().filenames(ImmutableList.sortedCopyOf(filenames)).build());\n }\n\n /**\n * Deletes all versions of the specified artifact from GCS.\n *\n * @param appName Application name.\n * @param userId User ID.\n * @param sessionId Session ID.\n * @param filename Artifact filename.\n * @return Completable indicating operation completion.\n */\n @Override\n public Completable deleteArtifact(\n String appName, String userId, String sessionId, String filename) {\n ImmutableList versions =\n listVersions(appName, userId, sessionId, filename).blockingGet();\n List blobIdsToDelete = new ArrayList<>();\n for (int version : versions) {\n String blobName = getBlobName(appName, userId, sessionId, filename, version);\n blobIdsToDelete.add(BlobId.of(bucketName, blobName));\n }\n\n if (!blobIdsToDelete.isEmpty()) {\n try {\n var unused = storageClient.delete(blobIdsToDelete);\n } catch (StorageException e) {\n throw new VerifyException(\"Failed to delete artifact versions from GCS\", e);\n }\n }\n return Completable.complete();\n }\n\n /**\n * Lists all available versions for a given artifact.\n *\n * @param appName Application name.\n * @param userId User ID.\n * @param sessionId Session ID.\n * @param filename Artifact filename.\n * @return Single with sorted list of version numbers.\n */\n @Override\n public Single> listVersions(\n String appName, String userId, String sessionId, String filename) {\n String prefix = getBlobPrefix(appName, userId, sessionId, filename);\n List versions = new ArrayList<>();\n try {\n for (Blob blob : storageClient.list(bucketName, BlobListOption.prefix(prefix)).iterateAll()) {\n String name = blob.getName();\n int versionDelimiterIndex = name.lastIndexOf('/'); // immediately before the version number\n if (versionDelimiterIndex != -1 && versionDelimiterIndex < name.length() - 1) {\n versions.add(Integer.parseInt(name.substring(versionDelimiterIndex + 1)));\n }\n }\n return Single.just(ImmutableList.sortedCopyOf(versions));\n } catch (StorageException e) {\n return Single.just(ImmutableList.of());\n }\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/agents/SequentialAgent.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.agents;\n\nimport com.google.adk.events.Event;\nimport com.google.common.collect.ImmutableList;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport io.reactivex.rxjava3.core.Flowable;\nimport java.util.List;\n\n/** An agent that runs its sub-agents sequentially. */\npublic class SequentialAgent extends BaseAgent {\n\n /**\n * Constructor for SequentialAgent.\n *\n * @param name The agent's name.\n * @param description The agent's description.\n * @param subAgents The list of sub-agents to run sequentially.\n * @param beforeAgentCallback Optional callback before the agent runs.\n * @param afterAgentCallback Optional callback after the agent runs.\n */\n private SequentialAgent(\n String name,\n String description,\n List subAgents,\n List beforeAgentCallback,\n List afterAgentCallback) {\n\n super(name, description, subAgents, beforeAgentCallback, afterAgentCallback);\n }\n\n /** Builder for {@link SequentialAgent}. */\n public static class Builder {\n private String name;\n private String description;\n private List subAgents;\n private ImmutableList beforeAgentCallback;\n private ImmutableList afterAgentCallback;\n\n @CanIgnoreReturnValue\n public Builder name(String name) {\n this.name = name;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder description(String description) {\n this.description = description;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder subAgents(List subAgents) {\n this.subAgents = subAgents;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder subAgents(BaseAgent... subAgents) {\n this.subAgents = ImmutableList.copyOf(subAgents);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeAgentCallback(Callbacks.BeforeAgentCallback beforeAgentCallback) {\n this.beforeAgentCallback = ImmutableList.of(beforeAgentCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeAgentCallback(\n List beforeAgentCallback) {\n this.beforeAgentCallback = CallbackUtil.getBeforeAgentCallbacks(beforeAgentCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterAgentCallback(Callbacks.AfterAgentCallback afterAgentCallback) {\n this.afterAgentCallback = ImmutableList.of(afterAgentCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterAgentCallback(List afterAgentCallback) {\n this.afterAgentCallback = CallbackUtil.getAfterAgentCallbacks(afterAgentCallback);\n return this;\n }\n\n public SequentialAgent build() {\n // TODO(b/410859954): Add validation for required fields like name.\n return new SequentialAgent(\n name, description, subAgents, beforeAgentCallback, afterAgentCallback);\n }\n }\n\n public static Builder builder() {\n return new Builder();\n }\n\n /**\n * Runs sub-agents sequentially.\n *\n * @param invocationContext Invocation context.\n * @return Flowable emitting events from sub-agents.\n */\n @Override\n protected Flowable runAsyncImpl(InvocationContext invocationContext) {\n return Flowable.fromIterable(subAgents())\n .concatMap(subAgent -> subAgent.runAsync(invocationContext));\n }\n\n /**\n * Runs sub-agents sequentially in live mode.\n *\n * @param invocationContext Invocation context.\n * @return Flowable emitting events from sub-agents in live mode.\n */\n @Override\n protected Flowable runLiveImpl(InvocationContext invocationContext) {\n return Flowable.fromIterable(subAgents())\n .concatMap(subAgent -> subAgent.runLive(invocationContext));\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/mcp/McpSessionManager.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools.mcp;\n\nimport io.modelcontextprotocol.client.McpClient;\nimport io.modelcontextprotocol.client.McpSyncClient;\nimport io.modelcontextprotocol.spec.McpClientTransport;\nimport io.modelcontextprotocol.spec.McpSchema.ClientCapabilities;\nimport io.modelcontextprotocol.spec.McpSchema.InitializeResult;\nimport java.time.Duration;\nimport java.util.Optional;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * Manages MCP client sessions.\n *\n *

This class provides methods for creating and initializing MCP client sessions, handling\n * different connection parameters and transport builders.\n */\n// TODO(b/413489523): Implement this class.\npublic class McpSessionManager {\n\n private final Object connectionParams; // ServerParameters or SseServerParameters\n private static final Logger logger = LoggerFactory.getLogger(McpSessionManager.class);\n\n public McpSessionManager(Object connectionParams) {\n this.connectionParams = connectionParams;\n }\n\n public McpSyncClient createSession() {\n return initializeSession(this.connectionParams);\n }\n\n public static McpSyncClient initializeSession(Object connectionParams) {\n return initializeSession(connectionParams, new DefaultMcpTransportBuilder());\n }\n\n public static McpSyncClient initializeSession(\n Object connectionParams, McpTransportBuilder transportBuilder) {\n Duration initializationTimeout = null;\n Duration requestTimeout = null;\n McpClientTransport transport = transportBuilder.build(connectionParams);\n if (connectionParams instanceof SseServerParameters sseServerParams) {\n initializationTimeout = sseServerParams.timeout();\n requestTimeout = sseServerParams.sseReadTimeout();\n }\n McpSyncClient client =\n McpClient.sync(transport)\n .initializationTimeout(\n Optional.ofNullable(initializationTimeout).orElse(Duration.ofSeconds(10)))\n .requestTimeout(Optional.ofNullable(requestTimeout).orElse(Duration.ofSeconds(10)))\n .capabilities(ClientCapabilities.builder().build())\n .build();\n InitializeResult initResult = client.initialize();\n logger.debug(\"Initialize Client Result: {}\", initResult);\n return client;\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/applicationintegrationtoolset/ApplicationIntegrationToolset.java", "package com.google.adk.tools.applicationintegrationtoolset;\n\nimport static com.google.common.base.Strings.isNullOrEmpty;\n\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.fasterxml.jackson.databind.node.ObjectNode;\nimport com.google.adk.agents.ReadonlyContext;\nimport com.google.adk.tools.BaseTool;\nimport com.google.adk.tools.BaseToolset;\nimport com.google.adk.tools.applicationintegrationtoolset.IntegrationConnectorTool.DefaultHttpExecutor;\nimport com.google.adk.tools.applicationintegrationtoolset.IntegrationConnectorTool.HttpExecutor;\nimport io.reactivex.rxjava3.core.Flowable;\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport org.jspecify.annotations.Nullable;\n\n/** Application Integration Toolset */\npublic class ApplicationIntegrationToolset implements BaseToolset {\n String project;\n String location;\n @Nullable String integration;\n @Nullable List triggers;\n @Nullable String connection;\n @Nullable Map> entityOperations;\n @Nullable List actions;\n String serviceAccountJson;\n @Nullable String toolNamePrefix;\n @Nullable String toolInstructions;\n public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();\n HttpExecutor httpExecutor;\n\n /**\n * ApplicationIntegrationToolset generates tools from a given Application Integration resource.\n *\n *

Example Usage:\n *\n *

integrationTool = new ApplicationIntegrationToolset( project=\"test-project\",\n * location=\"us-central1\", integration=\"test-integration\",\n * triggers=ImmutableList.of(\"api_trigger/test_trigger\", \"api_trigger/test_trigger_2\",\n * serviceAccountJson=\"{....}\"),connection=null,enitityOperations=null,actions=null,toolNamePrefix=\"test-integration-tool\",toolInstructions=\"This\n * tool is used to get response from test-integration.\");\n *\n *

connectionTool = new ApplicationIntegrationToolset( project=\"test-project\",\n * location=\"us-central1\", integration=null, triggers=null, connection=\"test-connection\",\n * entityOperations=ImmutableMap.of(\"Entity1\", ImmutableList.of(\"LIST\", \"GET\", \"UPDATE\")),\n * \"Entity2\", ImmutableList.of()), actions=ImmutableList.of(\"ExecuteCustomQuery\"),\n * serviceAccountJson=\"{....}\", toolNamePrefix=\"test-tool\", toolInstructions=\"This tool is used to\n * list, get and update issues in Jira.\");\n *\n * @param project The GCP project ID.\n * @param location The GCP location of integration.\n * @param integration The integration name.\n * @param triggers(Optional) The list of trigger ids in the integration.\n * @param connection(Optional) The connection name.\n * @param entityOperations(Optional) The entity operations.\n * @param actions(Optional) The actions.\n * @param serviceAccountJson(Optional) The service account configuration as a dictionary. Required\n * if not using default service credential. Used for fetching the Application Integration or\n * Integration Connector resource.\n * @param toolNamePrefix(Optional) The tool name prefix.\n * @param toolInstructions(Optional) The tool instructions.\n */\n public ApplicationIntegrationToolset(\n String project,\n String location,\n String integration,\n List triggers,\n String connection,\n Map> entityOperations,\n List actions,\n String serviceAccountJson,\n String toolNamePrefix,\n String toolInstructions) {\n this(\n project,\n location,\n integration,\n triggers,\n connection,\n entityOperations,\n actions,\n serviceAccountJson,\n toolNamePrefix,\n toolInstructions,\n new DefaultHttpExecutor().createExecutor(serviceAccountJson));\n }\n\n ApplicationIntegrationToolset(\n String project,\n String location,\n String integration,\n List triggers,\n String connection,\n Map> entityOperations,\n List actions,\n String serviceAccountJson,\n String toolNamePrefix,\n String toolInstructions,\n HttpExecutor httpExecutor) {\n this.project = project;\n this.location = location;\n this.integration = integration;\n this.triggers = triggers;\n this.connection = connection;\n this.entityOperations = entityOperations;\n this.actions = actions;\n this.serviceAccountJson = serviceAccountJson;\n this.toolNamePrefix = toolNamePrefix;\n this.toolInstructions = toolInstructions;\n this.httpExecutor = httpExecutor;\n }\n\n List getPathUrl(String openApiSchemaString) throws Exception {\n List pathUrls = new ArrayList<>();\n JsonNode topLevelNode = OBJECT_MAPPER.readTree(openApiSchemaString);\n JsonNode specNode = topLevelNode.path(\"openApiSpec\");\n if (specNode.isMissingNode() || !specNode.isTextual()) {\n throw new IllegalArgumentException(\n \"Failed to get OpenApiSpec, please check the project and region for the integration.\");\n }\n JsonNode rootNode = OBJECT_MAPPER.readTree(specNode.asText());\n JsonNode pathsNode = rootNode.path(\"paths\");\n Iterator> paths = pathsNode.fields();\n while (paths.hasNext()) {\n Map.Entry pathEntry = paths.next();\n String pathUrl = pathEntry.getKey();\n pathUrls.add(pathUrl);\n }\n return pathUrls;\n }\n\n private List getAllTools() throws Exception {\n String openApiSchemaString = null;\n List tools = new ArrayList<>();\n if (!isNullOrEmpty(this.integration)) {\n IntegrationClient integrationClient =\n new IntegrationClient(\n this.project,\n this.location,\n this.integration,\n this.triggers,\n null,\n null,\n null,\n this.httpExecutor);\n openApiSchemaString = integrationClient.generateOpenApiSpec();\n List pathUrls = getPathUrl(openApiSchemaString);\n for (String pathUrl : pathUrls) {\n String toolName = integrationClient.getOperationIdFromPathUrl(openApiSchemaString, pathUrl);\n if (toolName != null) {\n tools.add(\n new IntegrationConnectorTool(\n openApiSchemaString,\n pathUrl,\n toolName,\n toolInstructions,\n null,\n null,\n null,\n this.serviceAccountJson,\n this.httpExecutor));\n }\n }\n } else if (!isNullOrEmpty(this.connection)\n && (this.entityOperations != null || this.actions != null)) {\n IntegrationClient integrationClient =\n new IntegrationClient(\n this.project,\n this.location,\n null,\n null,\n this.connection,\n this.entityOperations,\n this.actions,\n this.httpExecutor);\n ObjectNode parentOpenApiSpec = OBJECT_MAPPER.createObjectNode();\n ObjectNode openApiSpec =\n integrationClient.getOpenApiSpecForConnection(toolNamePrefix, toolInstructions);\n String openApiSpecString = OBJECT_MAPPER.writeValueAsString(openApiSpec);\n parentOpenApiSpec.put(\"openApiSpec\", openApiSpecString);\n openApiSchemaString = OBJECT_MAPPER.writeValueAsString(parentOpenApiSpec);\n List pathUrls = getPathUrl(openApiSchemaString);\n for (String pathUrl : pathUrls) {\n String toolName = integrationClient.getOperationIdFromPathUrl(openApiSchemaString, pathUrl);\n if (!isNullOrEmpty(toolName)) {\n ConnectionsClient connectionsClient =\n new ConnectionsClient(\n this.project, this.location, this.connection, this.httpExecutor, OBJECT_MAPPER);\n ConnectionsClient.ConnectionDetails connectionDetails =\n connectionsClient.getConnectionDetails();\n\n tools.add(\n new IntegrationConnectorTool(\n openApiSchemaString,\n pathUrl,\n toolName,\n \"\",\n connectionDetails.name,\n connectionDetails.serviceName,\n connectionDetails.host,\n this.serviceAccountJson,\n this.httpExecutor));\n }\n }\n } else {\n throw new IllegalArgumentException(\n \"Invalid request, Either integration or (connection and\"\n + \" (entityOperations or actions)) should be provided.\");\n }\n\n return tools;\n }\n\n @Override\n public Flowable getTools(@Nullable ReadonlyContext readonlyContext) {\n try {\n List allTools = getAllTools();\n return Flowable.fromIterable(allTools);\n } catch (Exception e) {\n return Flowable.error(e);\n }\n }\n\n @Override\n public void close() throws Exception {\n // Nothing to close.\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/ToolContext.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools;\n\nimport com.google.adk.agents.CallbackContext;\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.artifacts.ListArtifactsResponse;\nimport com.google.adk.events.EventActions;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.List;\nimport java.util.Optional;\n\n/** ToolContext object provides a structured context for executing tools or functions. */\npublic class ToolContext extends CallbackContext {\n private Optional functionCallId = Optional.empty();\n\n private ToolContext(\n InvocationContext invocationContext,\n EventActions eventActions,\n Optional functionCallId) {\n super(invocationContext, eventActions);\n this.functionCallId = functionCallId;\n }\n\n public EventActions actions() {\n return this.eventActions;\n }\n\n public void setActions(EventActions actions) {\n this.eventActions = actions;\n }\n\n public Optional functionCallId() {\n return functionCallId;\n }\n\n public void functionCallId(String functionCallId) {\n this.functionCallId = Optional.ofNullable(functionCallId);\n }\n\n @SuppressWarnings(\"unused\")\n private void requestCredential() {\n // TODO: b/414678311 - Implement credential request logic. Make this public.\n throw new UnsupportedOperationException(\"Credential request not implemented yet.\");\n }\n\n @SuppressWarnings(\"unused\")\n private void getAuthResponse() {\n // TODO: b/414678311 - Implement auth response retrieval logic. Make this public.\n throw new UnsupportedOperationException(\"Auth response retrieval not implemented yet.\");\n }\n\n @SuppressWarnings(\"unused\")\n private void searchMemory() {\n // TODO: b/414680316 - Implement search memory logic. Make this public.\n throw new UnsupportedOperationException(\"Search memory not implemented yet.\");\n }\n\n /** Lists the filenames of the artifacts attached to the current session. */\n public Single> listArtifacts() {\n if (invocationContext.artifactService() == null) {\n throw new IllegalStateException(\"Artifact service is not initialized.\");\n }\n return invocationContext\n .artifactService()\n .listArtifactKeys(\n invocationContext.session().appName(),\n invocationContext.session().userId(),\n invocationContext.session().id())\n .map(ListArtifactsResponse::filenames);\n }\n\n public static Builder builder(InvocationContext invocationContext) {\n return new Builder(invocationContext);\n }\n\n public Builder toBuilder() {\n return new Builder(invocationContext)\n .actions(eventActions)\n .functionCallId(functionCallId.orElse(null));\n }\n\n /** Builder for {@link ToolContext}. */\n public static final class Builder {\n private final InvocationContext invocationContext;\n private EventActions eventActions = EventActions.builder().build(); // Default empty actions\n private Optional functionCallId = Optional.empty();\n\n private Builder(InvocationContext invocationContext) {\n this.invocationContext = invocationContext;\n }\n\n @CanIgnoreReturnValue\n public Builder actions(EventActions actions) {\n this.eventActions = actions;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder functionCallId(String functionCallId) {\n this.functionCallId = Optional.ofNullable(functionCallId);\n return this;\n }\n\n public ToolContext build() {\n return new ToolContext(invocationContext, eventActions, functionCallId);\n }\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/models/LlmResponse.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.models;\n\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.databind.annotation.JsonDeserialize;\nimport com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;\nimport com.google.adk.JsonBaseModel;\nimport com.google.auto.value.AutoValue;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport com.google.genai.types.Candidate;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.FinishReason;\nimport com.google.genai.types.GenerateContentResponse;\nimport com.google.genai.types.GenerateContentResponsePromptFeedback;\nimport com.google.genai.types.GroundingMetadata;\nimport java.util.List;\nimport java.util.Optional;\nimport javax.annotation.Nullable;\n\n/** Represents a response received from the LLM. */\n@AutoValue\n@JsonDeserialize(builder = LlmResponse.Builder.class)\npublic abstract class LlmResponse extends JsonBaseModel {\n\n LlmResponse() {}\n\n /**\n * Returns the content of the first candidate in the response, if available.\n *\n * @return An {@link Content} of the first {@link Candidate} in the {@link\n * GenerateContentResponse} if the response contains at least one candidate., or an empty\n * optional if no candidates are present in the response.\n */\n @JsonProperty(\"content\")\n public abstract Optional content();\n\n /**\n * Returns the grounding metadata of the first candidate in the response, if available.\n *\n * @return An {@link Optional} containing {@link GroundingMetadata} or empty.\n */\n @JsonProperty(\"groundingMetadata\")\n public abstract Optional groundingMetadata();\n\n /**\n * Indicates whether the text content is part of a unfinished text stream.\n *\n *

Only used for streaming mode and when the content is plain text.\n */\n @JsonProperty(\"partial\")\n public abstract Optional partial();\n\n /**\n * Indicates whether the response from the model is complete.\n *\n *

Only used for streaming mode.\n */\n @JsonProperty(\"turnComplete\")\n public abstract Optional turnComplete();\n\n /** Error code if the response is an error. Code varies by model. */\n @JsonProperty(\"errorCode\")\n public abstract Optional errorCode();\n\n /** Error message if the response is an error. */\n @JsonProperty(\"errorMessage\")\n public abstract Optional errorMessage();\n\n /**\n * Indicates that LLM was interrupted when generating the content. Usually it's due to user\n * interruption during a bidi streaming.\n */\n @JsonProperty(\"interrupted\")\n public abstract Optional interrupted();\n\n public abstract Builder toBuilder();\n\n /** Builder for constructing {@link LlmResponse} instances. */\n @AutoValue.Builder\n @JsonPOJOBuilder(buildMethodName = \"build\", withPrefix = \"\")\n public abstract static class Builder {\n\n @JsonCreator\n static LlmResponse.Builder jacksonBuilder() {\n return LlmResponse.builder();\n }\n\n @JsonProperty(\"content\")\n public abstract Builder content(Content content);\n\n @JsonProperty(\"interrupted\")\n public abstract Builder interrupted(@Nullable Boolean interrupted);\n\n public abstract Builder interrupted(Optional interrupted);\n\n @JsonProperty(\"groundingMetadata\")\n public abstract Builder groundingMetadata(@Nullable GroundingMetadata groundingMetadata);\n\n public abstract Builder groundingMetadata(Optional groundingMetadata);\n\n @JsonProperty(\"partial\")\n public abstract Builder partial(@Nullable Boolean partial);\n\n public abstract Builder partial(Optional partial);\n\n @JsonProperty(\"turnComplete\")\n public abstract Builder turnComplete(@Nullable Boolean turnComplete);\n\n public abstract Builder turnComplete(Optional turnComplete);\n\n @JsonProperty(\"errorCode\")\n public abstract Builder errorCode(@Nullable FinishReason errorCode);\n\n public abstract Builder errorCode(Optional errorCode);\n\n @JsonProperty(\"errorMessage\")\n public abstract Builder errorMessage(@Nullable String errorMessage);\n\n public abstract Builder errorMessage(Optional errorMessage);\n\n @CanIgnoreReturnValue\n public final Builder response(GenerateContentResponse response) {\n Optional> candidatesOpt = response.candidates();\n if (candidatesOpt.isPresent() && !candidatesOpt.get().isEmpty()) {\n Candidate candidate = candidatesOpt.get().get(0);\n if (candidate.content().isPresent()) {\n this.content(candidate.content().get());\n this.groundingMetadata(candidate.groundingMetadata());\n } else {\n candidate.finishReason().ifPresent(this::errorCode);\n candidate.finishMessage().ifPresent(this::errorMessage);\n }\n } else {\n Optional promptFeedbackOpt =\n response.promptFeedback();\n if (promptFeedbackOpt.isPresent()) {\n GenerateContentResponsePromptFeedback promptFeedback = promptFeedbackOpt.get();\n promptFeedback\n .blockReason()\n .ifPresent(reason -> this.errorCode(new FinishReason(reason.toString())));\n promptFeedback.blockReasonMessage().ifPresent(this::errorMessage);\n } else {\n this.errorCode(new FinishReason(\"Unknown error.\"));\n this.errorMessage(\"Unknown error.\");\n }\n }\n return this;\n }\n\n abstract LlmResponse autoBuild();\n\n public LlmResponse build() {\n return autoBuild();\n }\n }\n\n public static Builder builder() {\n return new AutoValue_LlmResponse.Builder();\n }\n\n public static LlmResponse create(List candidates) {\n GenerateContentResponse response =\n GenerateContentResponse.builder().candidates(candidates).build();\n return builder().response(response).build();\n }\n\n public static LlmResponse create(GenerateContentResponse response) {\n return builder().response(response).build();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/agents/CallbackContext.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.agents;\n\nimport com.google.adk.events.EventActions;\nimport com.google.adk.sessions.State;\nimport com.google.genai.types.Part;\nimport io.reactivex.rxjava3.core.Maybe;\nimport java.util.Optional;\n\n/** The context of various callbacks for an agent invocation. */\npublic class CallbackContext extends ReadonlyContext {\n\n protected EventActions eventActions;\n private final State state;\n\n /**\n * Initializes callback context.\n *\n * @param invocationContext Current invocation context.\n * @param eventActions Callback event actions.\n */\n public CallbackContext(InvocationContext invocationContext, EventActions eventActions) {\n super(invocationContext);\n this.eventActions = eventActions != null ? eventActions : EventActions.builder().build();\n this.state = new State(invocationContext.session().state(), this.eventActions.stateDelta());\n }\n\n /** Returns the delta-aware state of the current callback. */\n @Override\n public State state() {\n return state;\n }\n\n /** Returns the EventActions associated with this context. */\n public EventActions eventActions() {\n return eventActions;\n }\n\n /**\n * Loads an artifact from the artifact service associated with the current session.\n *\n * @param filename Artifact file name.\n * @param version Artifact version (optional).\n * @return loaded part, or empty if not found.\n * @throws IllegalStateException if the artifact service is not initialized.\n */\n public Maybe loadArtifact(String filename, Optional version) {\n if (invocationContext.artifactService() == null) {\n throw new IllegalStateException(\"Artifact service is not initialized.\");\n }\n return invocationContext\n .artifactService()\n .loadArtifact(\n invocationContext.appName(),\n invocationContext.userId(),\n invocationContext.session().id(),\n filename,\n version);\n }\n\n /**\n * Saves an artifact and records it as a delta for the current session.\n *\n * @param filename Artifact file name.\n * @param artifact Artifact content to save.\n * @throws IllegalStateException if the artifact service is not initialized.\n */\n public void saveArtifact(String filename, Part artifact) {\n if (invocationContext.artifactService() == null) {\n throw new IllegalStateException(\"Artifact service is not initialized.\");\n }\n var unused =\n invocationContext\n .artifactService()\n .saveArtifact(\n invocationContext.appName(),\n invocationContext.userId(),\n invocationContext.session().id(),\n filename,\n artifact);\n this.eventActions.artifactDelta().put(filename, artifact);\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/artifacts/InMemoryArtifactService.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.artifacts;\n\nimport static com.google.common.collect.ImmutableList.toImmutableList;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Streams;\nimport com.google.genai.types.Part;\nimport io.reactivex.rxjava3.core.Completable;\nimport io.reactivex.rxjava3.core.Maybe;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.stream.IntStream;\n\n/** An in-memory implementation of the {@link BaseArtifactService}. */\npublic final class InMemoryArtifactService implements BaseArtifactService {\n private final Map>>>> artifacts;\n\n public InMemoryArtifactService() {\n this.artifacts = new HashMap<>();\n }\n\n /**\n * Saves an artifact in memory and assigns a new version.\n *\n * @return Single with assigned version number.\n */\n @Override\n public Single saveArtifact(\n String appName, String userId, String sessionId, String filename, Part artifact) {\n List versions =\n artifacts\n .computeIfAbsent(appName, k -> new HashMap<>())\n .computeIfAbsent(userId, k -> new HashMap<>())\n .computeIfAbsent(sessionId, k -> new HashMap<>())\n .computeIfAbsent(filename, k -> new ArrayList<>());\n versions.add(artifact);\n return Single.just(versions.size() - 1);\n }\n\n /**\n * Loads an artifact by version or latest.\n *\n * @return Maybe with the artifact, or empty if not found.\n */\n @Override\n public Maybe loadArtifact(\n String appName, String userId, String sessionId, String filename, Optional version) {\n List versions =\n artifacts\n .getOrDefault(appName, new HashMap<>())\n .getOrDefault(userId, new HashMap<>())\n .getOrDefault(sessionId, new HashMap<>())\n .getOrDefault(filename, new ArrayList<>());\n\n if (versions.isEmpty()) {\n return Maybe.empty();\n }\n if (version.isPresent()) {\n int v = version.get();\n if (v >= 0 && v < versions.size()) {\n return Maybe.just(versions.get(v));\n } else {\n return Maybe.empty();\n }\n } else {\n return Maybe.fromOptional(Streams.findLast(versions.stream()));\n }\n }\n\n /**\n * Lists filenames of stored artifacts for the session.\n *\n * @return Single with list of artifact filenames.\n */\n @Override\n public Single listArtifactKeys(\n String appName, String userId, String sessionId) {\n return Single.just(\n ListArtifactsResponse.builder()\n .filenames(\n ImmutableList.copyOf(\n artifacts\n .getOrDefault(appName, new HashMap<>())\n .getOrDefault(userId, new HashMap<>())\n .getOrDefault(sessionId, new HashMap<>())\n .keySet()))\n .build());\n }\n\n /**\n * Deletes all versions of the given artifact.\n *\n * @return Completable indicating completion.\n */\n @Override\n public Completable deleteArtifact(\n String appName, String userId, String sessionId, String filename) {\n artifacts\n .getOrDefault(appName, new HashMap<>())\n .getOrDefault(userId, new HashMap<>())\n .getOrDefault(sessionId, new HashMap<>())\n .remove(filename);\n return Completable.complete();\n }\n\n /**\n * Lists all versions of the specified artifact.\n *\n * @return Single with list of version numbers.\n */\n @Override\n public Single> listVersions(\n String appName, String userId, String sessionId, String filename) {\n int size =\n artifacts\n .getOrDefault(appName, new HashMap<>())\n .getOrDefault(userId, new HashMap<>())\n .getOrDefault(sessionId, new HashMap<>())\n .getOrDefault(filename, new ArrayList<>())\n .size();\n if (size == 0) {\n return Single.just(ImmutableList.of());\n }\n return Single.just(IntStream.range(0, size).boxed().collect(toImmutableList()));\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/agents/ParallelAgent.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.agents;\n\nimport static com.google.common.base.Strings.isNullOrEmpty;\n\nimport com.google.adk.events.Event;\nimport com.google.common.collect.ImmutableList;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport io.reactivex.rxjava3.core.Flowable;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * A shell agent that runs its sub-agents in parallel in isolated manner.\n *\n *

This approach is beneficial for scenarios requiring multiple perspectives or attempts on a\n * single task, such as running different algorithms simultaneously or generating multiple responses\n * for review by a subsequent evaluation agent.\n */\npublic class ParallelAgent extends BaseAgent {\n\n /**\n * Constructor for ParallelAgent.\n *\n * @param name The agent's name.\n * @param description The agent's description.\n * @param subAgents The list of sub-agents to run sequentially.\n * @param beforeAgentCallback Optional callback before the agent runs.\n * @param afterAgentCallback Optional callback after the agent runs.\n */\n private ParallelAgent(\n String name,\n String description,\n List subAgents,\n List beforeAgentCallback,\n List afterAgentCallback) {\n\n super(name, description, subAgents, beforeAgentCallback, afterAgentCallback);\n }\n\n /** Builder for {@link ParallelAgent}. */\n public static class Builder {\n private String name;\n private String description;\n private List subAgents;\n private ImmutableList beforeAgentCallback;\n private ImmutableList afterAgentCallback;\n\n @CanIgnoreReturnValue\n public Builder name(String name) {\n this.name = name;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder description(String description) {\n this.description = description;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder subAgents(List subAgents) {\n this.subAgents = subAgents;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder subAgents(BaseAgent... subAgents) {\n this.subAgents = ImmutableList.copyOf(subAgents);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeAgentCallback(Callbacks.BeforeAgentCallback beforeAgentCallback) {\n this.beforeAgentCallback = ImmutableList.of(beforeAgentCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeAgentCallback(\n List beforeAgentCallback) {\n this.beforeAgentCallback = CallbackUtil.getBeforeAgentCallbacks(beforeAgentCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterAgentCallback(Callbacks.AfterAgentCallback afterAgentCallback) {\n this.afterAgentCallback = ImmutableList.of(afterAgentCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterAgentCallback(List afterAgentCallback) {\n this.afterAgentCallback = CallbackUtil.getAfterAgentCallbacks(afterAgentCallback);\n return this;\n }\n\n public ParallelAgent build() {\n return new ParallelAgent(\n name, description, subAgents, beforeAgentCallback, afterAgentCallback);\n }\n }\n\n public static Builder builder() {\n return new Builder();\n }\n\n /**\n * Sets the branch for the current agent in the invocation context.\n *\n *

Appends the agent name to the current branch, or sets it if undefined.\n *\n * @param currentAgent Current agent.\n * @param invocationContext Invocation context to update.\n */\n private static void setBranchForCurrentAgent(\n BaseAgent currentAgent, InvocationContext invocationContext) {\n String branch = invocationContext.branch().orElse(null);\n if (isNullOrEmpty(branch)) {\n invocationContext.branch(currentAgent.name());\n } else {\n invocationContext.branch(branch + \".\" + currentAgent.name());\n }\n }\n\n /**\n * Runs sub-agents in parallel and emits their events.\n *\n *

Sets the branch and merges event streams from all sub-agents.\n *\n * @param invocationContext Invocation context.\n * @return Flowable emitting events from all sub-agents.\n */\n @Override\n protected Flowable runAsyncImpl(InvocationContext invocationContext) {\n setBranchForCurrentAgent(this, invocationContext);\n\n List currentSubAgents = subAgents();\n if (currentSubAgents == null || currentSubAgents.isEmpty()) {\n return Flowable.empty();\n }\n\n List> agentFlowables = new ArrayList<>();\n for (BaseAgent subAgent : currentSubAgents) {\n agentFlowables.add(subAgent.runAsync(invocationContext));\n }\n return Flowable.merge(agentFlowables);\n }\n\n /**\n * Not supported for ParallelAgent.\n *\n * @param invocationContext Invocation context.\n * @return Flowable that always throws UnsupportedOperationException.\n */\n @Override\n protected Flowable runLiveImpl(InvocationContext invocationContext) {\n return Flowable.error(\n new UnsupportedOperationException(\"runLive is not defined for ParallelAgent yet.\"));\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/LongRunningFunctionTool.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools;\n\nimport java.lang.reflect.Method;\n\n/** A function tool that returns the result asynchronously. */\npublic class LongRunningFunctionTool extends FunctionTool {\n\n public static LongRunningFunctionTool create(Method func) {\n return new LongRunningFunctionTool(func);\n }\n\n public static LongRunningFunctionTool create(Class cls, String methodName) {\n for (Method method : cls.getMethods()) {\n if (method.getName().equals(methodName)) {\n return create(method);\n }\n }\n throw new IllegalArgumentException(\n String.format(\"Method %s not found in class %s.\", methodName, cls.getName()));\n }\n\n public static LongRunningFunctionTool create(Object instance, String methodName) {\n Class cls = instance.getClass();\n for (Method method : cls.getMethods()) {\n if (method.getName().equals(methodName)) {\n return new LongRunningFunctionTool(instance, method);\n }\n }\n throw new IllegalArgumentException(\n String.format(\"Method %s not found in class %s.\", methodName, cls.getName()));\n }\n\n private LongRunningFunctionTool(Method func) {\n super(null, func, /* isLongRunning= */ true);\n }\n\n private LongRunningFunctionTool(Object instance, Method func) {\n super(instance, func, /* isLongRunning= */ true);\n }\n}\n"], ["/adk-java/dev/src/main/java/com/google/adk/web/AgentCompilerLoader.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.web;\n\nimport com.google.adk.agents.BaseAgent;\nimport com.google.adk.web.config.AgentLoadingProperties;\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.PrintWriter;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Modifier;\nimport java.net.URISyntaxException;\nimport java.net.URL;\nimport java.net.URLClassLoader;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.nio.file.StandardCopyOption;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.LinkedHashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\nimport org.eclipse.jdt.core.compiler.batch.BatchCompiler;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.stereotype.Service;\n\n/**\n * Dynamically compiles and loads ADK {@link BaseAgent} implementations from source files. It\n * orchestrates the discovery of the ADK core JAR, compilation of agent sources using the Eclipse\n * JDT (ECJ) compiler, and loading of compiled agents into isolated classloaders. Agents are\n * identified by a public static field named {@code ROOT_AGENT}. Supports agent organization in\n * subdirectories or as individual {@code .java} files.\n */\n@Service\npublic class AgentCompilerLoader {\n private static final Logger logger = LoggerFactory.getLogger(AgentCompilerLoader.class);\n private final AgentLoadingProperties properties;\n private Path compiledAgentsOutputDir;\n private final String adkCoreJarPathForCompilation;\n\n /**\n * Initializes the loader with agent configuration and proactively attempts to locate the ADK core\n * JAR. This JAR, containing {@link BaseAgent} and other core ADK types, is crucial for agent\n * compilation. The location strategy (see {@link #locateAndPrepareAdkCoreJar()}) includes\n * handling directly available JARs and extracting nested JARs (e.g., in Spring Boot fat JARs) to\n * ensure it's available for the compilation classpath.\n *\n * @param properties Configuration detailing agent source locations and compilation settings.\n */\n public AgentCompilerLoader(AgentLoadingProperties properties) {\n this.properties = properties;\n this.adkCoreJarPathForCompilation = locateAndPrepareAdkCoreJar();\n }\n\n /**\n * Attempts to find the ADK core JAR, which provides {@link BaseAgent} and essential ADK classes\n * required for compiling dynamically loaded agents.\n *\n *

Strategies include:\n *\n *

    \n *
  • Checking if {@code BaseAgent.class} is loaded from a plain {@code .jar} file on the\n * classpath.\n *
  • Detecting and extracting the ADK core JAR if it's nested within a \"fat JAR\" (e.g., {@code\n * BOOT-INF/lib/} in Spring Boot applications). The extracted JAR is placed in a temporary\n * file for use during compilation.\n *
\n *\n * If located, its absolute path is returned for explicit inclusion in the compiler's classpath.\n * Returns an empty string if the JAR cannot be reliably pinpointed through these specific means,\n * in which case compilation will rely on broader classpath introspection.\n *\n * @return Absolute path to the ADK core JAR if found and prepared, otherwise an empty string.\n */\n private String locateAndPrepareAdkCoreJar() {\n try {\n URL agentClassUrl = BaseAgent.class.getProtectionDomain().getCodeSource().getLocation();\n if (agentClassUrl == null) {\n logger.warn(\"Could not get location for BaseAgent.class. ADK Core JAR might not be found.\");\n return \"\";\n }\n logger.debug(\"BaseAgent.class loaded from: {}\", agentClassUrl);\n\n if (\"file\".equals(agentClassUrl.getProtocol())) {\n Path path = Paths.get(agentClassUrl.toURI());\n if (path.toString().endsWith(\".jar\") && Files.exists(path)) {\n logger.debug(\n \"ADK Core JAR (or where BaseAgent resides) found directly on classpath: {}\",\n path.toAbsolutePath());\n return path.toAbsolutePath().toString();\n } else if (Files.isDirectory(path)) {\n logger.debug(\n \"BaseAgent.class found in directory (e.g., target/classes): {}. This path will be\"\n + \" part of classloader introspection.\",\n path.toAbsolutePath());\n return \"\";\n }\n } else if (\"jar\".equals(agentClassUrl.getProtocol())) { // Typically for nested JARs\n String urlPath = agentClassUrl.getPath();\n if (urlPath.startsWith(\"file:\")) {\n urlPath = urlPath.substring(\"file:\".length());\n }\n int firstSeparator = urlPath.indexOf(\"!/\");\n if (firstSeparator == -1) {\n logger.warn(\"Malformed JAR URL for BaseAgent.class: {}\", agentClassUrl);\n return \"\";\n }\n\n String mainJarPath = urlPath.substring(0, firstSeparator);\n String nestedPath = urlPath.substring(firstSeparator);\n\n if (nestedPath.startsWith(\"!/BOOT-INF/lib/\") && nestedPath.contains(\"google-adk-\")) {\n int nestedJarStartInPath = \"!/BOOT-INF/lib/\".length();\n int nestedJarEndInPath = nestedPath.indexOf(\"!/\", nestedJarStartInPath);\n if (nestedJarEndInPath > 0) {\n String nestedJarName = nestedPath.substring(nestedJarStartInPath, nestedJarEndInPath);\n String nestedJarUrlString =\n \"jar:file:\" + mainJarPath + \"!/BOOT-INF/lib/\" + nestedJarName;\n\n Path tempFile = Files.createTempFile(\"adk-core-extracted-\", \".jar\");\n try (InputStream is = new URL(nestedJarUrlString).openStream()) {\n Files.copy(is, tempFile, StandardCopyOption.REPLACE_EXISTING);\n }\n tempFile.toFile().deleteOnExit();\n logger.debug(\n \"Extracted ADK Core JAR '{}' from nested location to: {}\",\n nestedJarName,\n tempFile.toAbsolutePath());\n return tempFile.toAbsolutePath().toString();\n }\n } else if (mainJarPath.contains(\"google-adk-\") && mainJarPath.endsWith(\".jar\")) {\n File adkJar = new File(mainJarPath);\n if (adkJar.exists()) {\n logger.debug(\"ADK Core JAR identified as the outer JAR: {}\", adkJar.getAbsolutePath());\n return adkJar.getAbsolutePath();\n }\n }\n }\n } catch (Exception e) {\n logger.error(\"Error trying to locate or extract ADK Core JAR\", e);\n }\n logger.warn(\n \"ADK Core JAR could not be reliably located for compilation via locateAndPrepareAdkCoreJar.\"\n + \" Relying on classloader introspection.\");\n return \"\";\n }\n\n /**\n * Discovers, compiles, and loads agents from the configured source directory.\n *\n *

The process for each potential \"agent unit\" (a subdirectory or a root {@code .java} file):\n *\n *

    \n *
  1. Collects {@code .java} source files.\n *
  2. Compiles these sources using ECJ (see {@link #compileSourcesWithECJ(List, Path)}) into a\n * temporary, unit-specific output directory. This directory is cleaned up on JVM exit.\n *
  3. Creates a dedicated {@link URLClassLoader} for the compiled unit, isolating its classes.\n *
  4. Scans compiled classes for a public static field {@code ROOT_AGENT} assignable to {@link\n * BaseAgent}. This field serves as the designated entry point for an agent.\n *
  5. Instantiates and stores the {@link BaseAgent} if found, keyed by its name.\n *
\n *\n * This approach allows for dynamic addition of agents without pre-compilation and supports\n * independent classpaths per agent unit if needed (though current implementation uses a shared\n * parent classloader).\n *\n * @return A map of successfully loaded agent names to their {@link BaseAgent} instances. Returns\n * an empty map if the source directory isn't configured or no agents are found.\n * @throws IOException If an I/O error occurs (e.g., creating temp directories, reading sources).\n */\n public Map loadAgents() throws IOException {\n if (properties.getSourceDir() == null || properties.getSourceDir().isEmpty()) {\n logger.info(\n \"Agent source directory (adk.agents.source-dir) not configured. No dynamic agents will be\"\n + \" loaded.\");\n return Collections.emptyMap();\n }\n\n Path agentsSourceRoot = Paths.get(properties.getSourceDir());\n if (!Files.isDirectory(agentsSourceRoot)) {\n logger.warn(\"Agent source directory does not exist: {}\", agentsSourceRoot);\n return Collections.emptyMap();\n }\n\n this.compiledAgentsOutputDir = Files.createTempDirectory(\"adk-compiled-agents-\");\n this.compiledAgentsOutputDir.toFile().deleteOnExit();\n logger.debug(\"Compiling agents from {} to {}\", agentsSourceRoot, compiledAgentsOutputDir);\n\n Map loadedAgents = new HashMap<>();\n\n try (Stream stream = Files.list(agentsSourceRoot)) {\n List entries = stream.collect(Collectors.toList());\n\n for (Path entry : entries) {\n List javaFilesToCompile = new ArrayList<>();\n String agentUnitName;\n\n if (Files.isDirectory(entry)) {\n agentUnitName = entry.getFileName().toString();\n logger.debug(\"Processing agent sources from directory: {}\", agentUnitName);\n try (Stream javaFilesStream =\n Files.walk(entry)\n .filter(p -> p.toString().endsWith(\".java\") && Files.isRegularFile(p))) {\n javaFilesToCompile =\n javaFilesStream\n .map(p -> p.toAbsolutePath().toString())\n .collect(Collectors.toList());\n }\n } else if (Files.isRegularFile(entry) && entry.getFileName().toString().endsWith(\".java\")) {\n String fileName = entry.getFileName().toString();\n agentUnitName = fileName.substring(0, fileName.length() - \".java\".length());\n logger.debug(\"Processing agent source file: {}\", entry.getFileName());\n javaFilesToCompile.add(entry.toAbsolutePath().toString());\n } else {\n logger.trace(\"Skipping non-agent entry in agent source root: {}\", entry.getFileName());\n continue;\n }\n\n if (javaFilesToCompile.isEmpty()) {\n logger.debug(\"No .java files found for agent unit: {}\", agentUnitName);\n continue;\n }\n\n Path unitSpecificOutputDir = compiledAgentsOutputDir.resolve(agentUnitName);\n Files.createDirectories(unitSpecificOutputDir);\n\n boolean compilationSuccess =\n compileSourcesWithECJ(javaFilesToCompile, unitSpecificOutputDir);\n\n if (compilationSuccess) {\n try {\n List classLoaderUrls = new ArrayList<>();\n classLoaderUrls.add(unitSpecificOutputDir.toUri().toURL());\n\n URLClassLoader agentClassLoader =\n new URLClassLoader(\n classLoaderUrls.toArray(new URL[0]),\n AgentCompilerLoader.class.getClassLoader());\n\n Files.walk(unitSpecificOutputDir)\n .filter(p -> p.toString().endsWith(\".class\"))\n .forEach(\n classFile -> {\n try {\n String relativePath =\n unitSpecificOutputDir.relativize(classFile).toString();\n String className =\n relativePath\n .substring(0, relativePath.length() - \".class\".length())\n .replace(File.separatorChar, '.');\n\n Class loadedClass = agentClassLoader.loadClass(className);\n Field rootAgentField = null;\n try {\n rootAgentField = loadedClass.getField(\"ROOT_AGENT\");\n } catch (NoSuchFieldException e) {\n return;\n }\n\n if (Modifier.isStatic(rootAgentField.getModifiers())\n && BaseAgent.class.isAssignableFrom(rootAgentField.getType())) {\n BaseAgent agentInstance = (BaseAgent) rootAgentField.get(null);\n if (agentInstance != null) {\n if (loadedAgents.containsKey(agentInstance.name())) {\n logger.warn(\n \"Found another agent with name {}. This will overwrite the\"\n + \" original agent loaded with this name from unit {} using\"\n + \" class {}\",\n agentInstance.name(),\n agentUnitName,\n className);\n }\n loadedAgents.put(agentInstance.name(), agentInstance);\n logger.debug(\n \"Successfully loaded agent '{}' from unit: {} using class {}\",\n agentInstance.name(),\n agentUnitName,\n className);\n } else {\n logger.warn(\n \"ROOT_AGENT field in class {} from unit {} was null\",\n className,\n agentUnitName);\n }\n }\n } catch (ClassNotFoundException | IllegalAccessException e) {\n logger.error(\n \"Error loading or accessing agent from class file {} for unit {}\",\n classFile,\n agentUnitName,\n e);\n } catch (Exception e) {\n logger.error(\n \"Unexpected error processing class file {} for unit {}\",\n classFile,\n agentUnitName,\n e);\n }\n });\n } catch (Exception e) {\n logger.error(\n \"Error during class loading setup for unit {}: {}\",\n agentUnitName,\n e.getMessage(),\n e);\n }\n } else {\n logger.error(\"Compilation failed for agent unit: {}\", agentUnitName);\n }\n }\n }\n return loadedAgents;\n }\n\n /**\n * Compiles the given Java source files using the Eclipse JDT (ECJ) batch compiler.\n *\n *

Key aspects of the compilation process:\n *\n *

    \n *
  • Sets Java version to 17 (to align with core ADK library) and suppresses warnings by\n * default.\n *
  • Constructs the compilation classpath by:\n *
      \n *
    1. Introspecting the current classloader hierarchy ({@link URLClassLoader} instances)\n * to gather available JARs and class directories.\n *
    2. Falling back to {@code System.getProperty(\"java.class.path\")} if introspection\n * yields no results.\n *
    3. Explicitly adding the ADK Core JAR path (determined by {@link\n * #locateAndPrepareAdkCoreJar()}) to ensure {@link BaseAgent} and related types are\n * resolvable.\n *
    4. Appending any user-defined classpath entries from {@link\n * AgentLoadingProperties#getCompileClasspath()}.\n *
    \n *
  • Outputs compiled {@code .class} files to the specified {@code outputDir}.\n *
\n *\n * This method aims to provide a robust classpath for compiling agents in various runtime\n * environments, including IDEs, standard Java executions, and fat JAR deployments.\n *\n * @param javaFilePaths A list of absolute paths to {@code .java} files to be compiled.\n * @param outputDir The directory where compiled {@code .class} files will be placed.\n * @return {@code true} if compilation succeeds, {@code false} otherwise.\n */\n private boolean compileSourcesWithECJ(List javaFilePaths, Path outputDir) {\n List ecjArgs = new ArrayList<>();\n ecjArgs.add(\"-17\"); // Java version\n ecjArgs.add(\"-nowarn\");\n ecjArgs.add(\"-d\");\n ecjArgs.add(outputDir.toAbsolutePath().toString());\n\n Set classpathEntries = new LinkedHashSet<>();\n\n logger.debug(\"Attempting to derive ECJ classpath from classloader hierarchy...\");\n ClassLoader currentClassLoader = AgentCompilerLoader.class.getClassLoader();\n int classLoaderCount = 0;\n while (currentClassLoader != null) {\n classLoaderCount++;\n logger.debug(\n \"Inspecting classloader ({}) : {}\",\n classLoaderCount,\n currentClassLoader.getClass().getName());\n if (currentClassLoader instanceof java.net.URLClassLoader) {\n URL[] urls = ((java.net.URLClassLoader) currentClassLoader).getURLs();\n logger.debug(\n \" Found {} URLs in URLClassLoader {}\",\n urls.length,\n currentClassLoader.getClass().getName());\n for (URL url : urls) {\n try {\n if (\"file\".equals(url.getProtocol())) {\n String path = Paths.get(url.toURI()).toString();\n classpathEntries.add(path);\n logger.trace(\" Added to ECJ classpath: {}\", path);\n } else {\n logger.debug(\n \" Skipping non-file URL from classloader {}: {}\",\n currentClassLoader.getClass().getName(),\n url);\n }\n } catch (URISyntaxException | IllegalArgumentException e) {\n logger.warn(\n \" Could not convert URL to path or add to classpath from {}: {} (Error: {})\",\n currentClassLoader.getClass().getName(),\n url,\n e.getMessage());\n } catch (Exception e) {\n logger.warn(\n \" Unexpected error converting URL to path from {}: {} (Error: {})\",\n currentClassLoader.getClass().getName(),\n url,\n e.getMessage(),\n e);\n }\n }\n }\n currentClassLoader = currentClassLoader.getParent();\n }\n\n if (classpathEntries.isEmpty()) {\n logger.warn(\n \"No classpath entries derived from classloader hierarchy. \"\n + \"Falling back to System.getProperty(\\\"java.class.path\\\").\");\n String systemClasspath = System.getProperty(\"java.class.path\");\n if (systemClasspath != null && !systemClasspath.isEmpty()) {\n logger.debug(\"Using system classpath for ECJ (fallback): {}\", systemClasspath);\n classpathEntries.addAll(Arrays.asList(systemClasspath.split(File.pathSeparator)));\n } else {\n logger.error(\"System classpath (java.class.path) is also null or empty.\");\n }\n }\n\n if (this.adkCoreJarPathForCompilation != null && !this.adkCoreJarPathForCompilation.isEmpty()) {\n if (!classpathEntries.contains(this.adkCoreJarPathForCompilation)) {\n logger.debug(\n \"Adding ADK Core JAR path explicitly to ECJ classpath: {}\",\n this.adkCoreJarPathForCompilation);\n classpathEntries.add(this.adkCoreJarPathForCompilation);\n } else {\n logger.debug(\n \"ADK Core JAR path ({}) already found in derived ECJ classpath.\",\n this.adkCoreJarPathForCompilation);\n }\n } else if (classpathEntries.stream().noneMatch(p -> p.contains(\"google-adk\"))) {\n logger.error(\n \"ADK Core JAR path is missing and no 'google-adk' JAR found in derived classpath. \"\n + \"Compilation will likely fail to find BaseAgent.\");\n }\n\n if (properties.getCompileClasspath() != null && !properties.getCompileClasspath().isEmpty()) {\n String userClasspath = properties.getCompileClasspath();\n logger.info(\n \"Appending user-defined classpath (adk.agents.compile-classpath) to ECJ: {}\",\n userClasspath);\n classpathEntries.addAll(Arrays.asList(userClasspath.split(File.pathSeparator)));\n }\n\n if (!classpathEntries.isEmpty()) {\n String effectiveClasspath =\n classpathEntries.stream().collect(Collectors.joining(File.pathSeparator));\n ecjArgs.add(\"-cp\");\n ecjArgs.add(effectiveClasspath);\n logger.debug(\"Constructed ECJ classpath with {} entries\", classpathEntries.size());\n logger.debug(\"Final effective ECJ classpath: {}\", effectiveClasspath);\n } else {\n logger.error(\"ECJ Classpath is empty after all attempts. Compilation will fail.\");\n return false;\n }\n\n ecjArgs.addAll(javaFilePaths);\n\n logger.debug(\"ECJ Args: {}\", String.join(\" \", ecjArgs));\n\n PrintWriter outWriter = new PrintWriter(System.out, true);\n PrintWriter errWriter = new PrintWriter(System.err, true);\n\n boolean success =\n BatchCompiler.compile(ecjArgs.toArray(new String[0]), outWriter, errWriter, null);\n if (!success) {\n logger.error(\"ECJ Compilation failed. See console output for details.\");\n }\n return success;\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/sessions/ApiClient.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.StandardSystemProperty.JAVA_VERSION;\n\nimport com.google.auth.oauth2.GoogleCredentials;\nimport com.google.common.base.Ascii;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.genai.errors.GenAiIOException;\nimport com.google.genai.types.HttpOptions;\nimport java.io.IOException;\nimport java.time.Duration;\nimport java.util.Map;\nimport java.util.Optional;\nimport okhttp3.OkHttpClient;\nimport org.jspecify.annotations.Nullable;\n\n/** Interface for an API client which issues HTTP requests to the GenAI APIs. */\nabstract class ApiClient {\n OkHttpClient httpClient;\n // For Google AI APIs\n final Optional apiKey;\n // For Vertex AI APIs\n final Optional project;\n final Optional location;\n final Optional credentials;\n HttpOptions httpOptions;\n final boolean vertexAI;\n\n /** Constructs an ApiClient for Google AI APIs. */\n ApiClient(Optional apiKey, Optional customHttpOptions) {\n checkNotNull(apiKey, \"API Key cannot be null\");\n checkNotNull(customHttpOptions, \"customHttpOptions cannot be null\");\n\n try {\n this.apiKey = Optional.of(apiKey.orElse(System.getenv(\"GOOGLE_API_KEY\")));\n } catch (NullPointerException e) {\n throw new IllegalArgumentException(\n \"API key must either be provided or set in the environment variable\" + \" GOOGLE_API_KEY.\",\n e);\n }\n\n this.project = Optional.empty();\n this.location = Optional.empty();\n this.credentials = Optional.empty();\n this.vertexAI = false;\n\n this.httpOptions = defaultHttpOptions(/* vertexAI= */ false, this.location);\n\n if (customHttpOptions.isPresent()) {\n applyHttpOptions(customHttpOptions.get());\n }\n\n this.httpClient = createHttpClient(httpOptions.timeout());\n }\n\n ApiClient(\n Optional project,\n Optional location,\n Optional credentials,\n Optional customHttpOptions) {\n checkNotNull(project, \"project cannot be null\");\n checkNotNull(location, \"location cannot be null\");\n checkNotNull(credentials, \"credentials cannot be null\");\n checkNotNull(customHttpOptions, \"customHttpOptions cannot be null\");\n\n try {\n this.project = Optional.of(project.orElse(System.getenv(\"GOOGLE_CLOUD_PROJECT\")));\n } catch (NullPointerException e) {\n throw new IllegalArgumentException(\n \"Project must either be provided or set in the environment variable\"\n + \" GOOGLE_CLOUD_PROJECT.\",\n e);\n }\n if (this.project.get().isEmpty()) {\n throw new IllegalArgumentException(\"Project must not be empty.\");\n }\n\n try {\n this.location = Optional.of(location.orElse(System.getenv(\"GOOGLE_CLOUD_LOCATION\")));\n } catch (NullPointerException e) {\n throw new IllegalArgumentException(\n \"Location must either be provided or set in the environment variable\"\n + \" GOOGLE_CLOUD_LOCATION.\",\n e);\n }\n if (this.location.get().isEmpty()) {\n throw new IllegalArgumentException(\"Location must not be empty.\");\n }\n\n this.credentials = Optional.of(credentials.orElseGet(this::defaultCredentials));\n\n this.httpOptions = defaultHttpOptions(/* vertexAI= */ true, this.location);\n\n if (customHttpOptions.isPresent()) {\n applyHttpOptions(customHttpOptions.get());\n }\n this.apiKey = Optional.empty();\n this.vertexAI = true;\n this.httpClient = createHttpClient(httpOptions.timeout());\n }\n\n private OkHttpClient createHttpClient(Optional timeout) {\n OkHttpClient.Builder builder = new OkHttpClient().newBuilder();\n if (timeout.isPresent()) {\n builder.connectTimeout(Duration.ofMillis(timeout.get()));\n }\n return builder.build();\n }\n\n /** Sends a Http request given the http method, path, and request json string. */\n public abstract ApiResponse request(String httpMethod, String path, String requestJson);\n\n /** Returns the library version. */\n static String libraryVersion() {\n // TODO: Automate revisions to the SDK library version.\n String libraryLabel = \"google-genai-sdk/0.1.0\";\n String languageLabel = \"gl-java/\" + JAVA_VERSION.value();\n return libraryLabel + \" \" + languageLabel;\n }\n\n /** Returns whether the client is using Vertex AI APIs. */\n public boolean vertexAI() {\n return vertexAI;\n }\n\n /** Returns the project ID for Vertex AI APIs. */\n public @Nullable String project() {\n return project.orElse(null);\n }\n\n /** Returns the location for Vertex AI APIs. */\n public @Nullable String location() {\n return location.orElse(null);\n }\n\n /** Returns the API key for Google AI APIs. */\n public @Nullable String apiKey() {\n return apiKey.orElse(null);\n }\n\n /** Returns the HttpClient for API calls. */\n OkHttpClient httpClient() {\n return httpClient;\n }\n\n private Optional> getTimeoutHeader(HttpOptions httpOptionsToApply) {\n if (httpOptionsToApply.timeout().isPresent()) {\n int timeoutInSeconds = (int) Math.ceil((double) httpOptionsToApply.timeout().get() / 1000.0);\n // TODO(b/329147724): Document the usage of X-Server-Timeout header.\n return Optional.of(ImmutableMap.of(\"X-Server-Timeout\", Integer.toString(timeoutInSeconds)));\n }\n return Optional.empty();\n }\n\n private void applyHttpOptions(HttpOptions httpOptionsToApply) {\n HttpOptions.Builder mergedHttpOptionsBuilder = this.httpOptions.toBuilder();\n if (httpOptionsToApply.baseUrl().isPresent()) {\n mergedHttpOptionsBuilder.baseUrl(httpOptionsToApply.baseUrl().get());\n }\n if (httpOptionsToApply.apiVersion().isPresent()) {\n mergedHttpOptionsBuilder.apiVersion(httpOptionsToApply.apiVersion().get());\n }\n if (httpOptionsToApply.timeout().isPresent()) {\n mergedHttpOptionsBuilder.timeout(httpOptionsToApply.timeout().get());\n }\n if (httpOptionsToApply.headers().isPresent()) {\n ImmutableMap mergedHeaders =\n ImmutableMap.builder()\n .putAll(httpOptionsToApply.headers().orElse(ImmutableMap.of()))\n .putAll(this.httpOptions.headers().orElse(ImmutableMap.of()))\n .putAll(getTimeoutHeader(httpOptionsToApply).orElse(ImmutableMap.of()))\n .buildOrThrow();\n mergedHttpOptionsBuilder.headers(mergedHeaders);\n }\n this.httpOptions = mergedHttpOptionsBuilder.build();\n }\n\n static HttpOptions defaultHttpOptions(boolean vertexAI, Optional location) {\n ImmutableMap.Builder defaultHeaders = ImmutableMap.builder();\n defaultHeaders\n .put(\"Content-Type\", \"application/json\")\n .put(\"user-agent\", libraryVersion())\n .put(\"x-goog-api-client\", libraryVersion());\n\n HttpOptions.Builder defaultHttpOptionsBuilder =\n HttpOptions.builder().headers(defaultHeaders.buildOrThrow());\n\n if (vertexAI && location.isPresent()) {\n defaultHttpOptionsBuilder\n .baseUrl(\n Ascii.equalsIgnoreCase(location.get(), \"global\")\n ? \"https://aiplatform.googleapis.com\"\n : String.format(\"https://%s-aiplatform.googleapis.com\", location.get()))\n .apiVersion(\"v1beta1\");\n } else if (vertexAI && location.isEmpty()) {\n throw new IllegalArgumentException(\"Location must be provided for Vertex AI APIs.\");\n } else {\n defaultHttpOptionsBuilder\n .baseUrl(\"https://generativelanguage.googleapis.com\")\n .apiVersion(\"v1beta\");\n }\n return defaultHttpOptionsBuilder.build();\n }\n\n GoogleCredentials defaultCredentials() {\n try {\n return GoogleCredentials.getApplicationDefault()\n .createScoped(\"https://www.googleapis.com/auth/cloud-platform\");\n } catch (IOException e) {\n throw new GenAiIOException(\n \"Failed to get application default credentials, please explicitly provide credentials.\",\n e);\n }\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/sessions/SessionUtils.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.genai.types.Blob;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.Part;\nimport java.util.ArrayList;\nimport java.util.Base64;\nimport java.util.List;\nimport java.util.Optional;\n\n/** Utility functions for session service. */\npublic final class SessionUtils {\n\n public SessionUtils() {}\n\n /** Base64-encodes inline blobs in content. */\n public static Content encodeContent(Content content) {\n List encodedParts = new ArrayList<>();\n for (Part part : content.parts().orElse(ImmutableList.of())) {\n boolean isInlineDataPresent = false;\n if (part.inlineData() != null) {\n Optional inlineDataOptional = part.inlineData();\n if (inlineDataOptional.isPresent()) {\n Blob inlineDataBlob = inlineDataOptional.get();\n Optional dataOptional = inlineDataBlob.data();\n if (dataOptional.isPresent()) {\n byte[] dataBytes = dataOptional.get();\n byte[] encodedData = Base64.getEncoder().encode(dataBytes);\n encodedParts.add(\n part.toBuilder().inlineData(Blob.builder().data(encodedData).build()).build());\n isInlineDataPresent = true;\n }\n }\n }\n if (!isInlineDataPresent) {\n encodedParts.add(part);\n }\n }\n return toContent(encodedParts, content.role());\n }\n\n /** Decodes Base64-encoded inline blobs in content. */\n public static Content decodeContent(Content content) {\n List decodedParts = new ArrayList<>();\n for (Part part : content.parts().orElse(ImmutableList.of())) {\n boolean isInlineDataPresent = false;\n if (part.inlineData() != null) {\n Optional inlineDataOptional = part.inlineData();\n if (inlineDataOptional.isPresent()) {\n Blob inlineDataBlob = inlineDataOptional.get();\n Optional dataOptional = inlineDataBlob.data();\n if (dataOptional.isPresent()) {\n byte[] dataBytes = dataOptional.get();\n byte[] decodedData = Base64.getDecoder().decode(dataBytes);\n decodedParts.add(\n part.toBuilder().inlineData(Blob.builder().data(decodedData).build()).build());\n isInlineDataPresent = true;\n }\n }\n }\n if (!isInlineDataPresent) {\n decodedParts.add(part);\n }\n }\n return toContent(decodedParts, content.role());\n }\n\n /** Builds content from parts and optional role. */\n private static Content toContent(List parts, Optional role) {\n Content.Builder contentBuilder = Content.builder().parts(parts);\n role.ifPresent(contentBuilder::role);\n return contentBuilder.build();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/Telemetry.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk;\n\nimport static com.google.common.collect.ImmutableList.toImmutableList;\n\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.events.Event;\nimport com.google.adk.models.LlmRequest;\nimport com.google.adk.models.LlmResponse;\nimport com.google.common.collect.ImmutableList;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.Part;\nimport io.opentelemetry.api.GlobalOpenTelemetry;\nimport io.opentelemetry.api.trace.Span;\nimport io.opentelemetry.api.trace.Tracer;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * Utility class for capturing and reporting telemetry data within the ADK. This class provides\n * methods to trace various aspects of the agent's execution, including tool calls, tool responses,\n * LLM interactions, and data handling. It leverages OpenTelemetry for tracing and logging for\n * detailed information. These traces can then be exported through the ADK Dev Server UI.\n */\npublic class Telemetry {\n\n private static final Logger log = LoggerFactory.getLogger(Telemetry.class);\n private static final Tracer tracer = GlobalOpenTelemetry.getTracer(\"gcp.vertex.agent\");\n\n private Telemetry() {}\n\n /**\n * Traces tool call arguments.\n *\n * @param args The arguments to the tool call.\n */\n public static void traceToolCall(Map args) {\n Span span = Span.current();\n if (span == null || !span.getSpanContext().isValid()) {\n log.trace(\"traceToolCall: No valid span in current context.\");\n return;\n }\n\n span.setAttribute(\"gen_ai.system\", \"gcp.vertex.agent\");\n try {\n span.setAttribute(\n \"gcp.vertex.agent.tool_call_args\", JsonBaseModel.getMapper().writeValueAsString(args));\n } catch (JsonProcessingException e) {\n log.warn(\"traceToolCall: Failed to serialize tool call args to JSON\", e);\n }\n }\n\n /**\n * Traces tool response event.\n *\n * @param invocationContext The invocation context for the current agent run.\n * @param eventId The ID of the event.\n * @param functionResponseEvent The function response event.\n */\n public static void traceToolResponse(\n InvocationContext invocationContext, String eventId, Event functionResponseEvent) {\n Span span = Span.current();\n if (span == null || !span.getSpanContext().isValid()) {\n log.trace(\"traceToolResponse: No valid span in current context.\");\n return;\n }\n\n span.setAttribute(\"gen_ai.system\", \"gcp.vertex.agent\");\n span.setAttribute(\"gcp.vertex.agent.invocation_id\", invocationContext.invocationId());\n span.setAttribute(\"gcp.vertex.agent.event_id\", eventId);\n span.setAttribute(\"gcp.vertex.agent.tool_response\", functionResponseEvent.toJson());\n\n // Setting empty llm request and response (as the AdkDevServer UI expects these)\n span.setAttribute(\"gcp.vertex.agent.llm_request\", \"{}\");\n span.setAttribute(\"gcp.vertex.agent.llm_response\", \"{}\");\n if (invocationContext.session() != null && invocationContext.session().id() != null) {\n span.setAttribute(\"gcp.vertex.agent.session_id\", invocationContext.session().id());\n }\n }\n\n /**\n * Builds a dictionary representation of the LLM request for tracing. {@code GenerationConfig} is\n * included as a whole. For other fields like {@code Content}, parts that cannot be easily\n * serialized or are not needed for the trace (e.g., inlineData) are excluded.\n *\n * @param llmRequest The LlmRequest object.\n * @return A Map representation of the LLM request for tracing.\n */\n private static Map buildLlmRequestForTrace(LlmRequest llmRequest) {\n Map result = new HashMap<>();\n result.put(\"model\", llmRequest.model().orElse(null));\n llmRequest.config().ifPresent(config -> result.put(\"config\", config));\n\n List contentsList = new ArrayList<>();\n for (Content content : llmRequest.contents()) {\n ImmutableList filteredParts =\n content.parts().orElse(ImmutableList.of()).stream()\n .filter(part -> part.inlineData().isEmpty())\n .collect(toImmutableList());\n\n Content.Builder contentBuilder = Content.builder();\n content.role().ifPresent(contentBuilder::role);\n contentBuilder.parts(filteredParts);\n contentsList.add(contentBuilder.build());\n }\n result.put(\"contents\", contentsList);\n return result;\n }\n\n /**\n * Traces a call to the LLM.\n *\n * @param invocationContext The invocation context.\n * @param eventId The ID of the event associated with this LLM call/response.\n * @param llmRequest The LLM request object.\n * @param llmResponse The LLM response object.\n */\n public static void traceCallLlm(\n InvocationContext invocationContext,\n String eventId,\n LlmRequest llmRequest,\n LlmResponse llmResponse) {\n Span span = Span.current();\n if (span == null || !span.getSpanContext().isValid()) {\n log.trace(\"traceCallLlm: No valid span in current context.\");\n return;\n }\n\n span.setAttribute(\"gen_ai.system\", \"gcp.vertex.agent\");\n llmRequest.model().ifPresent(modelName -> span.setAttribute(\"gen_ai.request.model\", modelName));\n span.setAttribute(\"gcp.vertex.agent.invocation_id\", invocationContext.invocationId());\n span.setAttribute(\"gcp.vertex.agent.event_id\", eventId);\n\n if (invocationContext.session() != null && invocationContext.session().id() != null) {\n span.setAttribute(\"gcp.vertex.agent.session_id\", invocationContext.session().id());\n } else {\n log.trace(\n \"traceCallLlm: InvocationContext session or session ID is null, cannot set\"\n + \" gcp.vertex.agent.session_id\");\n }\n\n try {\n span.setAttribute(\n \"gcp.vertex.agent.llm_request\",\n JsonBaseModel.getMapper().writeValueAsString(buildLlmRequestForTrace(llmRequest)));\n span.setAttribute(\"gcp.vertex.agent.llm_response\", llmResponse.toJson());\n } catch (JsonProcessingException e) {\n log.warn(\"traceCallLlm: Failed to serialize LlmRequest or LlmResponse to JSON\", e);\n }\n }\n\n /**\n * Traces the sending of data (history or new content) to the agent/model.\n *\n * @param invocationContext The invocation context.\n * @param eventId The ID of the event, if applicable.\n * @param data A list of content objects being sent.\n */\n public static void traceSendData(\n InvocationContext invocationContext, String eventId, List data) {\n Span span = Span.current();\n if (span == null || !span.getSpanContext().isValid()) {\n log.trace(\"traceSendData: No valid span in current context.\");\n return;\n }\n\n span.setAttribute(\"gcp.vertex.agent.invocation_id\", invocationContext.invocationId());\n if (eventId != null && !eventId.isEmpty()) {\n span.setAttribute(\"gcp.vertex.agent.event_id\", eventId);\n }\n\n if (invocationContext.session() != null && invocationContext.session().id() != null) {\n span.setAttribute(\"gcp.vertex.agent.session_id\", invocationContext.session().id());\n }\n\n try {\n List> dataList = new ArrayList<>();\n if (data != null) {\n for (Content content : data) {\n if (content != null) {\n dataList.add(\n JsonBaseModel.getMapper()\n .convertValue(content, new TypeReference>() {}));\n }\n }\n }\n span.setAttribute(\"gcp.vertex.agent.data\", JsonBaseModel.toJsonString(dataList));\n } catch (IllegalStateException e) {\n log.warn(\"traceSendData: Failed to serialize data to JSON\", e);\n }\n }\n\n /**\n * Gets the tracer.\n *\n * @return The tracer.\n */\n public static Tracer getTracer() {\n return tracer;\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/llmflows/Examples.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows.llmflows;\n\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.agents.LlmAgent;\nimport com.google.adk.examples.ExampleUtils;\nimport com.google.adk.models.LlmRequest;\nimport com.google.common.collect.ImmutableList;\nimport io.reactivex.rxjava3.core.Single;\n\n/** {@link RequestProcessor} that populates examples in LLM request. */\npublic final class Examples implements RequestProcessor {\n\n public Examples() {}\n\n @Override\n public Single processRequest(\n InvocationContext context, LlmRequest request) {\n if (!(context.agent() instanceof LlmAgent)) {\n throw new IllegalArgumentException(\"Agent in InvocationContext is not an instance of Agent.\");\n }\n LlmAgent agent = (LlmAgent) context.agent();\n LlmRequest.Builder builder = request.toBuilder();\n\n String query =\n context.userContent().isPresent()\n ? context.userContent().get().parts().get().get(0).text().orElse(\"\")\n : \"\";\n agent\n .exampleProvider()\n .ifPresent(\n exampleProvider ->\n builder.appendInstructions(\n ImmutableList.of(ExampleUtils.buildExampleSi(exampleProvider, query))));\n return Single.just(\n RequestProcessor.RequestProcessingResult.create(builder.build(), ImmutableList.of()));\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/Annotations.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools;\n\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.ElementType.PARAMETER;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\n/** Annotations for tools. */\npublic final class Annotations {\n\n /** The annotation for binding the 'Schema' input. */\n @Target({METHOD, PARAMETER})\n @Retention(RetentionPolicy.RUNTIME)\n public @interface Schema {\n String name() default \"\";\n\n String description() default \"\";\n }\n\n private Annotations() {}\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/agents/RunConfig.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.agents;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport com.google.genai.types.AudioTranscriptionConfig;\nimport com.google.genai.types.Modality;\nimport com.google.genai.types.SpeechConfig;\nimport org.jspecify.annotations.Nullable;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/** Configuration to modify an agent's LLM's underlying behavior. */\n@AutoValue\npublic abstract class RunConfig {\n private static final Logger logger = LoggerFactory.getLogger(RunConfig.class);\n\n /** Streaming mode for the runner. Required for BaseAgent.runLive() to work. */\n public enum StreamingMode {\n NONE,\n SSE,\n BIDI\n }\n\n public abstract @Nullable SpeechConfig speechConfig();\n\n public abstract ImmutableList responseModalities();\n\n public abstract boolean saveInputBlobsAsArtifacts();\n\n public abstract StreamingMode streamingMode();\n\n public abstract @Nullable AudioTranscriptionConfig outputAudioTranscription();\n\n public abstract int maxLlmCalls();\n\n public static Builder builder() {\n return new AutoValue_RunConfig.Builder()\n .setSaveInputBlobsAsArtifacts(false)\n .setResponseModalities(ImmutableList.of())\n .setStreamingMode(StreamingMode.NONE)\n .setMaxLlmCalls(500);\n }\n\n public static Builder builder(RunConfig runConfig) {\n return new AutoValue_RunConfig.Builder()\n .setSaveInputBlobsAsArtifacts(runConfig.saveInputBlobsAsArtifacts())\n .setStreamingMode(runConfig.streamingMode())\n .setMaxLlmCalls(runConfig.maxLlmCalls())\n .setResponseModalities(runConfig.responseModalities())\n .setSpeechConfig(runConfig.speechConfig())\n .setOutputAudioTranscription(runConfig.outputAudioTranscription());\n }\n\n /** Builder for {@link RunConfig}. */\n @AutoValue.Builder\n public abstract static class Builder {\n\n @CanIgnoreReturnValue\n public abstract Builder setSpeechConfig(SpeechConfig speechConfig);\n\n @CanIgnoreReturnValue\n public abstract Builder setResponseModalities(Iterable responseModalities);\n\n @CanIgnoreReturnValue\n public abstract Builder setSaveInputBlobsAsArtifacts(boolean saveInputBlobsAsArtifacts);\n\n @CanIgnoreReturnValue\n public abstract Builder setStreamingMode(StreamingMode streamingMode);\n\n @CanIgnoreReturnValue\n public abstract Builder setOutputAudioTranscription(\n AudioTranscriptionConfig outputAudioTranscription);\n\n @CanIgnoreReturnValue\n public abstract Builder setMaxLlmCalls(int maxLlmCalls);\n\n abstract RunConfig autoBuild();\n\n public RunConfig build() {\n RunConfig runConfig = autoBuild();\n if (runConfig.maxLlmCalls() < 0) {\n logger.warn(\n \"maxLlmCalls is negative. This will result in no enforcement on total\"\n + \" number of llm calls that will be made for a run. This may not be ideal, as this\"\n + \" could result in a never ending communication between the model and the agent in\"\n + \" certain cases.\");\n }\n return runConfig;\n }\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/utils/InstructionUtils.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.utils;\n\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.sessions.Session;\nimport com.google.adk.sessions.State;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.genai.types.Part;\nimport io.reactivex.rxjava3.core.Maybe;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.regex.MatchResult;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\n/** Utility methods for handling instruction templates. */\npublic final class InstructionUtils {\n\n private static final Pattern INSTRUCTION_PLACEHOLDER_PATTERN =\n Pattern.compile(\"\\\\{+[^\\\\{\\\\}]*\\\\}+\");\n\n private InstructionUtils() {}\n\n /**\n * Populates placeholders in an instruction template string with values from the session state or\n * loaded artifacts.\n *\n *

Placeholder Syntax:\n *\n *

Placeholders are enclosed by one or more curly braces at the start and end, e.g., {@code\n * {key}} or {@code {{key}}}. The core {@code key} is extracted from whatever is between the\n * innermost pair of braces after trimming whitespace and possibly removing the {@code ?} which\n * denotes optionality (e.g. {@code {key?}}). The {@code key} itself must not contain curly\n * braces. For typical usage, a single pair of braces like {@code {my_variable}} is standard.\n *\n *

The extracted {@code key} determines the source and name of the value:\n *\n *

    \n *
  • Session State Variables: The {@code key} (e.g., {@code \"variable_name\"} or {@code\n * \"prefix:variable_name\"}) refers to a variable in session state.\n *
      \n *
    • Simple name: {@code {variable_name}}. The {@code variable_name} part must be a\n * valid identifier as per {@link #isValidStateName(String)}. Invalid names will\n * result in the placeholder being returned as is.\n *
    • Prefixed name: {@code {prefix:variable_name}}. Valid prefixes are: {@value\n * com.google.adk.sessions.State#APP_PREFIX}, {@value\n * com.google.adk.sessions.State#USER_PREFIX}, and {@value\n * com.google.adk.sessions.State#TEMP_PREFIX} The part of the name following the\n * prefix must also be a valid identifier. Invalid prefixes will result in the\n * placeholder being returned as is.\n *
    \n *
  • Artifacts: The {@code key} starts with \"{@code artifact.}\" (e.g., {@code\n * \"artifact.file_name\"}).\n *
  • Optional Placeholders: A {@code key} can be marked as optional by appending a\n * question mark {@code ?} at its very end, inside the braces.\n *
      \n *
    • Example: {@code {optional_variable?}}, {@code {{artifact.optional_file.txt?}}}\n *
    • If an optional placeholder cannot be resolved (e.g., variable not found, artifact\n * not found), it is replaced with an empty string.\n *
    \n *
\n *\n * Example Usage:\n *\n *
{@code\n   * InvocationContext context = ...; // Assume this is initialized with session and artifact service\n   * Session session = context.session();\n   *\n   * session.state().put(\"user:name\", \"Alice\");\n   *\n   * context.artifactService().saveArtifact(\n   *     session.appName(), session.userId(), session.id(), \"knowledge.txt\", Part.fromText(\"Origins of the universe: At first, there was-\"));\n   *\n   * String template = \"You are {user:name}'s assistant. Answer questions based on your knowledge. Your knowledge: {artifact.knowledge.txt}.\" +\n   *                   \" Your extra knowledge: {artifact.missing_artifact.txt?}\";\n   *\n   * Single populatedStringSingle = InstructionUtils.injectSessionState(context, template);\n   * populatedStringSingle.subscribe(\n   *     result -> System.out.println(result),\n   *     // Expected: \"You are Alice's assistant. Answer questions based on your knowledge. Your knowledge: Origins of the universe: At first, there was-. Your extra knowledge: \"\n   *     error -> System.err.println(\"Error populating template: \" + error.getMessage())\n   * );\n   * }
\n *\n * @param context The invocation context providing access to session state and artifact services.\n * @param template The instruction template string containing placeholders to be populated.\n * @return A {@link Single} that will emit the populated instruction string upon successful\n * resolution of all non-optional placeholders. Emits the original template if it is empty or\n * contains no placeholders that are processed.\n * @throws NullPointerException if the template or context is null.\n * @throws IllegalArgumentException if a non-optional variable or artifact is not found.\n */\n public static Single injectSessionState(InvocationContext context, String template) {\n if (template == null) {\n return Single.error(new NullPointerException(\"template cannot be null\"));\n }\n if (context == null) {\n return Single.error(new NullPointerException(\"context cannot be null\"));\n }\n Matcher matcher = INSTRUCTION_PLACEHOLDER_PATTERN.matcher(template);\n List> parts = new ArrayList<>();\n int lastEnd = 0;\n\n while (matcher.find()) {\n if (matcher.start() > lastEnd) {\n parts.add(Single.just(template.substring(lastEnd, matcher.start())));\n }\n MatchResult matchResult = matcher.toMatchResult();\n parts.add(resolveMatchAsync(context, matchResult));\n lastEnd = matcher.end();\n }\n if (lastEnd < template.length()) {\n parts.add(Single.just(template.substring(lastEnd)));\n }\n\n if (parts.isEmpty()) {\n return Single.just(template);\n }\n\n return Single.zip(\n parts,\n objects -> {\n StringBuilder sb = new StringBuilder();\n for (Object obj : objects) {\n sb.append(obj);\n }\n return sb.toString();\n });\n }\n\n private static Single resolveMatchAsync(InvocationContext context, MatchResult match) {\n String placeholder = match.group();\n String varNameFromPlaceholder =\n placeholder.replaceAll(\"^\\\\{+\", \"\").replaceAll(\"\\\\}+$\", \"\").trim();\n\n final boolean optional;\n final String cleanVarName;\n if (varNameFromPlaceholder.endsWith(\"?\")) {\n optional = true;\n cleanVarName = varNameFromPlaceholder.substring(0, varNameFromPlaceholder.length() - 1);\n } else {\n optional = false;\n cleanVarName = varNameFromPlaceholder;\n }\n\n if (cleanVarName.startsWith(\"artifact.\")) {\n final String artifactName = cleanVarName.substring(\"artifact.\".length());\n Session session = context.session();\n\n Maybe artifactMaybe =\n context\n .artifactService()\n .loadArtifact(\n session.appName(),\n session.userId(),\n session.id(),\n artifactName,\n Optional.empty());\n\n return artifactMaybe\n .map(Part::toJson)\n .switchIfEmpty(\n Single.defer(\n () -> {\n if (optional) {\n return Single.just(\"\");\n } else {\n return Single.error(\n new IllegalArgumentException(\n String.format(\"Artifact %s not found.\", artifactName)));\n }\n }));\n\n } else if (!isValidStateName(cleanVarName)) {\n return Single.just(placeholder);\n } else if (context.session().state().containsKey(cleanVarName)) {\n Object value = context.session().state().get(cleanVarName);\n return Single.just(String.valueOf(value));\n } else if (optional) {\n return Single.just(\"\");\n } else {\n return Single.error(\n new IllegalArgumentException(\n String.format(\"Context variable not found: `%s`.\", cleanVarName)));\n }\n }\n\n /**\n * Checks if a given string is a valid state variable name.\n *\n *

A valid state variable name must either:\n *\n *

    \n *
  • Be a valid identifier (as defined by {@link Character#isJavaIdentifierStart(int)} and\n * {@link Character#isJavaIdentifierPart(int)}).\n *
  • Start with a valid prefix ({@value com.google.adk.sessions.State#APP_PREFIX}, {@value\n * com.google.adk.sessions.State#USER_PREFIX}, or {@value\n * com.google.adk.sessions.State#TEMP_PREFIX}) followed by a valid identifier.\n *
\n *\n * @param varName The string to check.\n * @return True if the string is a valid state variable name, false otherwise.\n */\n private static boolean isValidStateName(String varName) {\n if (varName.isEmpty()) {\n return false;\n }\n String[] parts = varName.split(\":\", 2);\n if (parts.length == 1) {\n return isValidIdentifier(parts[0]);\n }\n\n if (parts.length == 2) {\n String prefixPart = parts[0] + \":\";\n ImmutableSet validPrefixes =\n ImmutableSet.of(State.APP_PREFIX, State.USER_PREFIX, State.TEMP_PREFIX);\n if (validPrefixes.contains(prefixPart)) {\n return isValidIdentifier(parts[1]);\n }\n }\n return false;\n }\n\n private static boolean isValidIdentifier(String s) {\n if (s.isEmpty()) {\n return false;\n }\n if (!Character.isJavaIdentifierStart(s.charAt(0))) {\n return false;\n }\n for (int i = 1; i < s.length(); i++) {\n if (!Character.isJavaIdentifierPart(s.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/agents/LiveRequest.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.agents;\n\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.databind.annotation.JsonDeserialize;\nimport com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;\nimport com.google.adk.JsonBaseModel;\nimport com.google.auto.value.AutoValue;\nimport com.google.common.base.Preconditions;\nimport com.google.genai.types.Blob;\nimport com.google.genai.types.Content;\nimport java.util.Optional;\nimport javax.annotation.Nullable;\n\n/** Represents a request to be sent to a live connection to the LLM model. */\n@AutoValue\n@JsonDeserialize(builder = LiveRequest.Builder.class)\npublic abstract class LiveRequest extends JsonBaseModel {\n\n LiveRequest() {}\n\n /**\n * Returns the content of the request.\n *\n *

If set, send the content to the model in turn-by-turn mode.\n *\n * @return An optional {@link Content} object containing the content of the request.\n */\n @JsonProperty(\"content\")\n public abstract Optional content();\n\n /**\n * Returns the blob of the request.\n *\n *

If set, send the blob to the model in realtime mode.\n *\n * @return An optional {@link Blob} object containing the blob of the request.\n */\n @JsonProperty(\"blob\")\n public abstract Optional blob();\n\n /**\n * Returns whether the connection should be closed.\n *\n *

If set to true, the connection will be closed after the request is sent.\n *\n * @return A boolean indicating whether the connection should be closed.\n */\n @JsonProperty(\"close\")\n public abstract Optional close();\n\n /** Extracts boolean value from the close field or returns false if unset. */\n public boolean shouldClose() {\n return close().orElse(false);\n }\n\n /** Builder for constructing {@link LiveRequest} instances. */\n @AutoValue.Builder\n @JsonPOJOBuilder(buildMethodName = \"build\", withPrefix = \"\")\n public abstract static class Builder {\n @JsonProperty(\"content\")\n public abstract Builder content(@Nullable Content content);\n\n public abstract Builder content(Optional content);\n\n @JsonProperty(\"blob\")\n public abstract Builder blob(@Nullable Blob blob);\n\n public abstract Builder blob(Optional blob);\n\n @JsonProperty(\"close\")\n public abstract Builder close(@Nullable Boolean close);\n\n public abstract Builder close(Optional close);\n\n abstract LiveRequest autoBuild();\n\n public final LiveRequest build() {\n LiveRequest request = autoBuild();\n Preconditions.checkState(\n request.content().isPresent()\n || request.blob().isPresent()\n || request.close().isPresent(),\n \"One of content, blob, or close must be set\");\n return request;\n }\n }\n\n public static Builder builder() {\n return new AutoValue_LiveRequest.Builder().close(false);\n }\n\n public abstract Builder toBuilder();\n\n /** Deserializes a Json string to a {@link LiveRequest} object. */\n public static LiveRequest fromJsonString(String json) {\n return JsonBaseModel.fromJsonString(json, LiveRequest.class);\n }\n\n @JsonCreator\n static LiveRequest.Builder jacksonBuilder() {\n return LiveRequest.builder();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/agents/InvocationContext.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.agents;\n\nimport com.google.adk.artifacts.BaseArtifactService;\nimport com.google.adk.exceptions.LlmCallsLimitExceededException;\nimport com.google.adk.sessions.BaseSessionService;\nimport com.google.adk.sessions.Session;\nimport com.google.genai.types.Content;\nimport java.util.Objects;\nimport java.util.Optional;\nimport java.util.UUID;\nimport javax.annotation.Nullable;\n\n/** The context for an agent invocation. */\npublic class InvocationContext {\n\n private final BaseSessionService sessionService;\n private final BaseArtifactService artifactService;\n private final Optional liveRequestQueue;\n\n private Optional branch;\n private final String invocationId;\n private BaseAgent agent;\n private final Session session;\n\n private final Optional userContent;\n private final RunConfig runConfig;\n private boolean endInvocation;\n private final InvocationCostManager invocationCostManager = new InvocationCostManager();\n\n private InvocationContext(\n BaseSessionService sessionService,\n BaseArtifactService artifactService,\n Optional liveRequestQueue,\n Optional branch,\n String invocationId,\n BaseAgent agent,\n Session session,\n Optional userContent,\n RunConfig runConfig,\n boolean endInvocation) {\n this.sessionService = sessionService;\n this.artifactService = artifactService;\n this.liveRequestQueue = liveRequestQueue;\n this.branch = branch;\n this.invocationId = invocationId;\n this.agent = agent;\n this.session = session;\n this.userContent = userContent;\n this.runConfig = runConfig;\n this.endInvocation = endInvocation;\n }\n\n public static InvocationContext create(\n BaseSessionService sessionService,\n BaseArtifactService artifactService,\n String invocationId,\n BaseAgent agent,\n Session session,\n Content userContent,\n RunConfig runConfig) {\n return new InvocationContext(\n sessionService,\n artifactService,\n Optional.empty(),\n /* branch= */ Optional.empty(),\n invocationId,\n agent,\n session,\n Optional.ofNullable(userContent),\n runConfig,\n false);\n }\n\n public static InvocationContext create(\n BaseSessionService sessionService,\n BaseArtifactService artifactService,\n BaseAgent agent,\n Session session,\n LiveRequestQueue liveRequestQueue,\n RunConfig runConfig) {\n return new InvocationContext(\n sessionService,\n artifactService,\n Optional.ofNullable(liveRequestQueue),\n /* branch= */ Optional.empty(),\n InvocationContext.newInvocationContextId(),\n agent,\n session,\n Optional.empty(),\n runConfig,\n false);\n }\n\n public static InvocationContext copyOf(InvocationContext other) {\n return new InvocationContext(\n other.sessionService,\n other.artifactService,\n other.liveRequestQueue,\n other.branch,\n other.invocationId,\n other.agent,\n other.session,\n other.userContent,\n other.runConfig,\n other.endInvocation);\n }\n\n public BaseSessionService sessionService() {\n return sessionService;\n }\n\n public BaseArtifactService artifactService() {\n return artifactService;\n }\n\n public Optional liveRequestQueue() {\n return liveRequestQueue;\n }\n\n public String invocationId() {\n return invocationId;\n }\n\n public void branch(@Nullable String branch) {\n this.branch = Optional.ofNullable(branch);\n }\n\n public Optional branch() {\n return branch;\n }\n\n public BaseAgent agent() {\n return agent;\n }\n\n public void agent(BaseAgent agent) {\n this.agent = agent;\n }\n\n public Session session() {\n return session;\n }\n\n public Optional userContent() {\n return userContent;\n }\n\n public RunConfig runConfig() {\n return runConfig;\n }\n\n public boolean endInvocation() {\n return endInvocation;\n }\n\n public void setEndInvocation(boolean endInvocation) {\n this.endInvocation = endInvocation;\n }\n\n public String appName() {\n return session.appName();\n }\n\n public String userId() {\n return session.userId();\n }\n\n public static String newInvocationContextId() {\n return \"e-\" + UUID.randomUUID();\n }\n\n public void incrementLlmCallsCount() throws LlmCallsLimitExceededException {\n this.invocationCostManager.incrementAndEnforceLlmCallsLimit(this.runConfig);\n }\n\n private static class InvocationCostManager {\n private int numberOfLlmCalls = 0;\n\n public void incrementAndEnforceLlmCallsLimit(RunConfig runConfig)\n throws LlmCallsLimitExceededException {\n this.numberOfLlmCalls++;\n\n if (runConfig != null\n && runConfig.maxLlmCalls() > 0\n && this.numberOfLlmCalls > runConfig.maxLlmCalls()) {\n throw new LlmCallsLimitExceededException(\n \"Max number of llm calls limit of \" + runConfig.maxLlmCalls() + \" exceeded\");\n }\n }\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (!(o instanceof InvocationContext that)) {\n return false;\n }\n return endInvocation == that.endInvocation\n && Objects.equals(sessionService, that.sessionService)\n && Objects.equals(artifactService, that.artifactService)\n && Objects.equals(liveRequestQueue, that.liveRequestQueue)\n && Objects.equals(branch, that.branch)\n && Objects.equals(invocationId, that.invocationId)\n && Objects.equals(agent, that.agent)\n && Objects.equals(session, that.session)\n && Objects.equals(userContent, that.userContent)\n && Objects.equals(runConfig, that.runConfig);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(\n sessionService,\n artifactService,\n liveRequestQueue,\n branch,\n invocationId,\n agent,\n session,\n userContent,\n runConfig,\n endInvocation);\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/mcp/DefaultMcpTransportBuilder.java", "package com.google.adk.tools.mcp;\n\nimport com.google.common.collect.ImmutableMap;\nimport io.modelcontextprotocol.client.transport.HttpClientSseClientTransport;\nimport io.modelcontextprotocol.client.transport.ServerParameters;\nimport io.modelcontextprotocol.client.transport.StdioClientTransport;\nimport io.modelcontextprotocol.spec.McpClientTransport;\nimport java.util.Collection;\nimport java.util.Optional;\n\n/**\n * The default builder for creating MCP client transports. Supports StdioClientTransport based on\n * {@link ServerParameters} and the standard HttpClientSseClientTransport based on {@link\n * SseServerParameters}.\n */\npublic class DefaultMcpTransportBuilder implements McpTransportBuilder {\n\n @Override\n public McpClientTransport build(Object connectionParams) {\n if (connectionParams instanceof ServerParameters serverParameters) {\n return new StdioClientTransport(serverParameters);\n } else if (connectionParams instanceof SseServerParameters sseServerParams) {\n return HttpClientSseClientTransport.builder(sseServerParams.url())\n .sseEndpoint(\"sse\")\n .customizeRequest(\n builder ->\n Optional.ofNullable(sseServerParams.headers())\n .map(ImmutableMap::entrySet)\n .stream()\n .flatMap(Collection::stream)\n .forEach(\n entry ->\n builder.header(\n entry.getKey(),\n Optional.ofNullable(entry.getValue())\n .map(Object::toString)\n .orElse(\"\"))))\n .build();\n } else {\n throw new IllegalArgumentException(\n \"DefaultMcpTransportBuilder supports only ServerParameters or SseServerParameters, but\"\n + \" got \"\n + connectionParams.getClass().getName());\n }\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/agents/Callbacks.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.agents;\n\nimport com.google.adk.models.LlmRequest;\nimport com.google.adk.models.LlmResponse;\nimport com.google.adk.tools.BaseTool;\nimport com.google.adk.tools.ToolContext;\nimport com.google.genai.types.Content;\nimport io.reactivex.rxjava3.core.Maybe;\nimport java.util.Map;\nimport java.util.Optional;\n\n/** Functional interfaces for agent lifecycle callbacks. */\npublic final class Callbacks {\n\n interface BeforeModelCallbackBase {}\n\n @FunctionalInterface\n public interface BeforeModelCallback extends BeforeModelCallbackBase {\n /**\n * Async callback before LLM invocation.\n *\n * @param callbackContext Callback context.\n * @param llmRequest LLM request.\n * @return response override, or empty to continue.\n */\n Maybe call(CallbackContext callbackContext, LlmRequest llmRequest);\n }\n\n /**\n * Helper interface to allow for sync beforeModelCallback. The function is wrapped into an async\n * one before being processed further.\n */\n @FunctionalInterface\n public interface BeforeModelCallbackSync extends BeforeModelCallbackBase {\n Optional call(CallbackContext callbackContext, LlmRequest llmRequest);\n }\n\n interface AfterModelCallbackBase {}\n\n @FunctionalInterface\n public interface AfterModelCallback extends AfterModelCallbackBase {\n /**\n * Async callback after LLM response.\n *\n * @param callbackContext Callback context.\n * @param llmResponse LLM response.\n * @return modified response, or empty to keep original.\n */\n Maybe call(CallbackContext callbackContext, LlmResponse llmResponse);\n }\n\n /**\n * Helper interface to allow for sync afterModelCallback. The function is wrapped into an async\n * one before being processed further.\n */\n @FunctionalInterface\n public interface AfterModelCallbackSync extends AfterModelCallbackBase {\n Optional call(CallbackContext callbackContext, LlmResponse llmResponse);\n }\n\n interface BeforeAgentCallbackBase {}\n\n @FunctionalInterface\n public interface BeforeAgentCallback extends BeforeAgentCallbackBase {\n /**\n * Async callback before agent runs.\n *\n * @param callbackContext Callback context.\n * @return content override, or empty to continue.\n */\n Maybe call(CallbackContext callbackContext);\n }\n\n /**\n * Helper interface to allow for sync beforeAgentCallback. The function is wrapped into an async\n * one before being processed further.\n */\n @FunctionalInterface\n public interface BeforeAgentCallbackSync extends BeforeAgentCallbackBase {\n Optional call(CallbackContext callbackContext);\n }\n\n interface AfterAgentCallbackBase {}\n\n @FunctionalInterface\n public interface AfterAgentCallback extends AfterAgentCallbackBase {\n /**\n * Async callback after agent runs.\n *\n * @param callbackContext Callback context.\n * @return modified content, or empty to keep original.\n */\n Maybe call(CallbackContext callbackContext);\n }\n\n /**\n * Helper interface to allow for sync afterAgentCallback. The function is wrapped into an async\n * one before being processed further.\n */\n @FunctionalInterface\n public interface AfterAgentCallbackSync extends AfterAgentCallbackBase {\n Optional call(CallbackContext callbackContext);\n }\n\n interface BeforeToolCallbackBase {}\n\n @FunctionalInterface\n public interface BeforeToolCallback extends BeforeToolCallbackBase {\n /**\n * Async callback before tool runs.\n *\n * @param invocationContext Invocation context.\n * @param baseTool Tool instance.\n * @param input Tool input arguments.\n * @param toolContext Tool context.\n * @return override result, or empty to continue.\n */\n Maybe> call(\n InvocationContext invocationContext,\n BaseTool baseTool,\n Map input,\n ToolContext toolContext);\n }\n\n /**\n * Helper interface to allow for sync beforeToolCallback. The function is wrapped into an async\n * one before being processed further.\n */\n @FunctionalInterface\n public interface BeforeToolCallbackSync extends BeforeToolCallbackBase {\n Optional> call(\n InvocationContext invocationContext,\n BaseTool baseTool,\n Map input,\n ToolContext toolContext);\n }\n\n interface AfterToolCallbackBase {}\n\n @FunctionalInterface\n public interface AfterToolCallback extends AfterToolCallbackBase {\n /**\n * Async callback after tool runs.\n *\n * @param invocationContext Invocation context.\n * @param baseTool Tool instance.\n * @param input Tool input arguments.\n * @param toolContext Tool context.\n * @param response Raw tool response.\n * @return processed result, or empty to keep original.\n */\n Maybe> call(\n InvocationContext invocationContext,\n BaseTool baseTool,\n Map input,\n ToolContext toolContext,\n Object response);\n }\n\n /**\n * Helper interface to allow for sync afterToolCallback. The function is wrapped into an async one\n * before being processed further.\n */\n @FunctionalInterface\n public interface AfterToolCallbackSync extends AfterToolCallbackBase {\n Optional> call(\n InvocationContext invocationContext,\n BaseTool baseTool,\n Map input,\n ToolContext toolContext,\n Object response);\n }\n\n private Callbacks() {}\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/events/EventActions.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.google.adk.events;\n\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.databind.annotation.JsonDeserialize;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport com.google.genai.types.Part;\nimport java.util.Objects;\nimport java.util.Optional;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentMap;\nimport javax.annotation.Nullable;\n\n/** Represents the actions attached to an event. */\n// TODO - b/414081262 make json wire camelCase\n@JsonDeserialize(builder = EventActions.Builder.class)\npublic class EventActions {\n\n private Optional skipSummarization = Optional.empty();\n private ConcurrentMap stateDelta = new ConcurrentHashMap<>();\n private ConcurrentMap artifactDelta = new ConcurrentHashMap<>();\n private Optional transferToAgent = Optional.empty();\n private Optional escalate = Optional.empty();\n private ConcurrentMap> requestedAuthConfigs =\n new ConcurrentHashMap<>();\n private Optional endInvocation = Optional.empty();\n\n /** Default constructor for Jackson. */\n public EventActions() {}\n\n @JsonProperty(\"skipSummarization\")\n public Optional skipSummarization() {\n return skipSummarization;\n }\n\n public void setSkipSummarization(@Nullable Boolean skipSummarization) {\n this.skipSummarization = Optional.ofNullable(skipSummarization);\n }\n\n public void setSkipSummarization(Optional skipSummarization) {\n this.skipSummarization = skipSummarization;\n }\n\n public void setSkipSummarization(boolean skipSummarization) {\n this.skipSummarization = Optional.of(skipSummarization);\n }\n\n @JsonProperty(\"stateDelta\")\n public ConcurrentMap stateDelta() {\n return stateDelta;\n }\n\n public void setStateDelta(ConcurrentMap stateDelta) {\n this.stateDelta = stateDelta;\n }\n\n @JsonProperty(\"artifactDelta\")\n public ConcurrentMap artifactDelta() {\n return artifactDelta;\n }\n\n public void setArtifactDelta(ConcurrentMap artifactDelta) {\n this.artifactDelta = artifactDelta;\n }\n\n @JsonProperty(\"transferToAgent\")\n public Optional transferToAgent() {\n return transferToAgent;\n }\n\n public void setTransferToAgent(Optional transferToAgent) {\n this.transferToAgent = transferToAgent;\n }\n\n public void setTransferToAgent(String transferToAgent) {\n this.transferToAgent = Optional.ofNullable(transferToAgent);\n }\n\n @JsonProperty(\"escalate\")\n public Optional escalate() {\n return escalate;\n }\n\n public void setEscalate(Optional escalate) {\n this.escalate = escalate;\n }\n\n public void setEscalate(boolean escalate) {\n this.escalate = Optional.of(escalate);\n }\n\n @JsonProperty(\"requestedAuthConfigs\")\n public ConcurrentMap> requestedAuthConfigs() {\n return requestedAuthConfigs;\n }\n\n public void setRequestedAuthConfigs(\n ConcurrentMap> requestedAuthConfigs) {\n this.requestedAuthConfigs = requestedAuthConfigs;\n }\n\n @JsonProperty(\"endInvocation\")\n public Optional endInvocation() {\n return endInvocation;\n }\n\n public void setEndInvocation(Optional endInvocation) {\n this.endInvocation = endInvocation;\n }\n\n public void setEndInvocation(boolean endInvocation) {\n this.endInvocation = Optional.of(endInvocation);\n }\n\n public static Builder builder() {\n return new Builder();\n }\n\n public Builder toBuilder() {\n return new Builder(this);\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (!(o instanceof EventActions that)) {\n return false;\n }\n return Objects.equals(skipSummarization, that.skipSummarization)\n && Objects.equals(stateDelta, that.stateDelta)\n && Objects.equals(artifactDelta, that.artifactDelta)\n && Objects.equals(transferToAgent, that.transferToAgent)\n && Objects.equals(escalate, that.escalate)\n && Objects.equals(requestedAuthConfigs, that.requestedAuthConfigs)\n && Objects.equals(endInvocation, that.endInvocation);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(\n skipSummarization,\n stateDelta,\n artifactDelta,\n transferToAgent,\n escalate,\n requestedAuthConfigs,\n endInvocation);\n }\n\n /** Builder for {@link EventActions}. */\n public static class Builder {\n private Optional skipSummarization = Optional.empty();\n private ConcurrentMap stateDelta = new ConcurrentHashMap<>();\n private ConcurrentMap artifactDelta = new ConcurrentHashMap<>();\n private Optional transferToAgent = Optional.empty();\n private Optional escalate = Optional.empty();\n private ConcurrentMap> requestedAuthConfigs =\n new ConcurrentHashMap<>();\n private Optional endInvocation = Optional.empty();\n\n public Builder() {}\n\n private Builder(EventActions eventActions) {\n this.skipSummarization = eventActions.skipSummarization();\n this.stateDelta = new ConcurrentHashMap<>(eventActions.stateDelta());\n this.artifactDelta = new ConcurrentHashMap<>(eventActions.artifactDelta());\n this.transferToAgent = eventActions.transferToAgent();\n this.escalate = eventActions.escalate();\n this.requestedAuthConfigs = new ConcurrentHashMap<>(eventActions.requestedAuthConfigs());\n this.endInvocation = eventActions.endInvocation();\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"skipSummarization\")\n public Builder skipSummarization(boolean skipSummarization) {\n this.skipSummarization = Optional.of(skipSummarization);\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"stateDelta\")\n public Builder stateDelta(ConcurrentMap value) {\n this.stateDelta = value;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"artifactDelta\")\n public Builder artifactDelta(ConcurrentMap value) {\n this.artifactDelta = value;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"transferToAgent\")\n public Builder transferToAgent(String agentId) {\n this.transferToAgent = Optional.ofNullable(agentId);\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"escalate\")\n public Builder escalate(boolean escalate) {\n this.escalate = Optional.of(escalate);\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"requestedAuthConfigs\")\n public Builder requestedAuthConfigs(\n ConcurrentMap> value) {\n this.requestedAuthConfigs = value;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"endInvocation\")\n public Builder endInvocation(boolean endInvocation) {\n this.endInvocation = Optional.of(endInvocation);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder merge(EventActions other) {\n if (other.skipSummarization().isPresent()) {\n this.skipSummarization = other.skipSummarization();\n }\n if (other.stateDelta() != null) {\n this.stateDelta.putAll(other.stateDelta());\n }\n if (other.artifactDelta() != null) {\n this.artifactDelta.putAll(other.artifactDelta());\n }\n if (other.transferToAgent().isPresent()) {\n this.transferToAgent = other.transferToAgent();\n }\n if (other.escalate().isPresent()) {\n this.escalate = other.escalate();\n }\n if (other.requestedAuthConfigs() != null) {\n this.requestedAuthConfigs.putAll(other.requestedAuthConfigs());\n }\n if (other.endInvocation().isPresent()) {\n this.endInvocation = other.endInvocation();\n }\n return this;\n }\n\n public EventActions build() {\n EventActions eventActions = new EventActions();\n eventActions.setSkipSummarization(this.skipSummarization);\n eventActions.setStateDelta(this.stateDelta);\n eventActions.setArtifactDelta(this.artifactDelta);\n eventActions.setTransferToAgent(this.transferToAgent);\n eventActions.setEscalate(this.escalate);\n eventActions.setRequestedAuthConfigs(this.requestedAuthConfigs);\n eventActions.setEndInvocation(this.endInvocation);\n return eventActions;\n }\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/BaseToolset.java", "package com.google.adk.tools;\n\nimport com.google.adk.agents.ReadonlyContext;\nimport io.reactivex.rxjava3.core.Flowable;\nimport java.util.List;\nimport java.util.Optional;\n\n/** Base interface for toolsets. */\npublic interface BaseToolset extends AutoCloseable {\n\n /**\n * Return all tools in the toolset based on the provided context.\n *\n * @param readonlyContext Context used to filter tools available to the agent.\n * @return A Single emitting a list of tools available under the specified context.\n */\n Flowable getTools(ReadonlyContext readonlyContext);\n\n /**\n * Performs cleanup and releases resources held by the toolset.\n *\n *

NOTE: This method is invoked, for example, at the end of an agent server's lifecycle or when\n * the toolset is no longer needed. Implementations should ensure that any open connections,\n * files, or other managed resources are properly released to prevent leaks.\n */\n @Override\n void close() throws Exception;\n\n /**\n * Helper method to be used by implementers that returns true if the given tool is in the provided\n * list of tools of if testing against the given ToolPredicate returns true (otherwise false).\n *\n * @param tool The tool to check.\n * @param toolFilter An Optional containing either a ToolPredicate or a List of tool names.\n * @param readonlyContext The current context.\n * @return true if the tool is selected.\n */\n default boolean isToolSelected(\n BaseTool tool, Optional toolFilter, Optional readonlyContext) {\n if (toolFilter.isEmpty()) {\n return true;\n }\n Object filter = toolFilter.get();\n if (filter instanceof ToolPredicate toolPredicate) {\n return toolPredicate.test(tool, readonlyContext);\n }\n if (filter instanceof List) {\n @SuppressWarnings(\"unchecked\")\n List toolNames = (List) filter;\n return toolNames.contains(tool.name());\n }\n return false;\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/llmflows/AutoFlow.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows.llmflows;\n\nimport com.google.common.collect.ImmutableList;\nimport java.util.Optional;\n\n/** LLM flow with automatic agent transfer support. */\npublic class AutoFlow extends SingleFlow {\n\n /** Adds {@link AgentTransfer} to base request processors. */\n private static final ImmutableList REQUEST_PROCESSORS =\n ImmutableList.builder()\n .addAll(SingleFlow.REQUEST_PROCESSORS)\n .add(new AgentTransfer())\n .build();\n\n /** No additional response processors. */\n private static final ImmutableList RESPONSE_PROCESSORS = ImmutableList.of();\n\n public AutoFlow() {\n this(/* maxSteps= */ Optional.empty());\n }\n\n public AutoFlow(Optional maxSteps) {\n super(REQUEST_PROCESSORS, RESPONSE_PROCESSORS, maxSteps);\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/models/LlmRegistry.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.models;\n\nimport java.util.Map;\nimport java.util.concurrent.ConcurrentHashMap;\n\n/** Central registry for managing Large Language Model (LLM) instances. */\npublic final class LlmRegistry {\n\n /** A thread-safe cache mapping model names to LLM instances. */\n private static final Map instances = new ConcurrentHashMap<>();\n\n /** The factory interface for creating LLM instances. */\n @FunctionalInterface\n public interface LlmFactory {\n BaseLlm create(String modelName);\n }\n\n /** Map of model name patterns regex to factories. */\n private static final Map llmFactories = new ConcurrentHashMap<>();\n\n /** Registers default LLM factories, e.g. for Gemini models. */\n static {\n registerLlm(\"gemini-.*\", modelName -> Gemini.builder().modelName(modelName).build());\n }\n\n /**\n * Registers a factory for model names matching the given regex pattern.\n *\n * @param modelNamePattern Regex pattern for matching model names.\n * @param factory Factory to create LLM instances.\n */\n public static void registerLlm(String modelNamePattern, LlmFactory factory) {\n llmFactories.put(modelNamePattern, factory);\n }\n\n /**\n * Returns an LLM instance for the given model name, using a cached or new factory-created\n * instance.\n *\n * @param modelName Model name to look up.\n * @return Matching {@link BaseLlm} instance.\n * @throws IllegalArgumentException If no factory matches the model name.\n */\n public static BaseLlm getLlm(String modelName) {\n return instances.computeIfAbsent(modelName, LlmRegistry::createLlm);\n }\n\n /**\n * Creates a {@link BaseLlm} by matching the model name against registered factories.\n *\n * @param modelName Model name to match.\n * @return A new {@link BaseLlm} instance.\n * @throws IllegalArgumentException If no factory matches the model name.\n */\n private static BaseLlm createLlm(String modelName) {\n for (Map.Entry entry : llmFactories.entrySet()) {\n if (modelName.matches(entry.getKey())) {\n return entry.getValue().create(modelName);\n }\n }\n throw new IllegalArgumentException(\"Unsupported model: \" + modelName);\n }\n\n /**\n * Registers an LLM factory for testing purposes. Clears cached instances matching the given\n * pattern to ensure test isolation.\n *\n * @param modelNamePattern Regex pattern for matching model names.\n * @param factory The {@link LlmFactory} to register.\n */\n static void registerTestLlm(String modelNamePattern, LlmFactory factory) {\n llmFactories.put(modelNamePattern, factory);\n // Clear any cached instances that match this pattern to ensure test isolation.\n instances.keySet().removeIf(modelName -> modelName.matches(modelNamePattern));\n }\n\n private LlmRegistry() {}\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/mcp/SseServerParameters.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools.mcp;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableMap;\nimport java.time.Duration;\nimport java.util.Map;\nimport javax.annotation.Nullable;\n\n/** Parameters for establishing a MCP Server-Sent Events (SSE) connection. */\n@AutoValue\npublic abstract class SseServerParameters {\n\n /** The URL of the SSE server. */\n public abstract String url();\n\n /** Optional headers to include in the SSE connection request. */\n @Nullable\n public abstract ImmutableMap headers();\n\n /** The timeout for the initial connection attempt. */\n public abstract Duration timeout();\n\n /** The timeout for reading data from the SSE stream. */\n public abstract Duration sseReadTimeout();\n\n /** Creates a new builder for {@link SseServerParameters}. */\n public static Builder builder() {\n return new AutoValue_SseServerParameters.Builder()\n .timeout(Duration.ofSeconds(5))\n .sseReadTimeout(Duration.ofMinutes(5));\n }\n\n /** Builder for {@link SseServerParameters}. */\n @AutoValue.Builder\n public abstract static class Builder {\n /** Sets the URL of the SSE server. */\n public abstract Builder url(String url);\n\n /** Sets the headers for the SSE connection request. */\n public abstract Builder headers(@Nullable Map headers);\n\n /** Sets the timeout for the initial connection attempt. */\n public abstract Builder timeout(Duration timeout);\n\n /** Sets the timeout for reading data from the SSE stream. */\n public abstract Builder sseReadTimeout(Duration sseReadTimeout);\n\n /** Builds a new {@link SseServerParameters} instance. */\n public abstract SseServerParameters build();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/llmflows/Instructions.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows.llmflows;\n\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.agents.LlmAgent;\nimport com.google.adk.agents.ReadonlyContext;\nimport com.google.adk.models.LlmRequest;\nimport com.google.adk.utils.InstructionUtils;\nimport com.google.common.collect.ImmutableList;\nimport io.reactivex.rxjava3.core.Single;\n\n/** {@link RequestProcessor} that handles instructions and global instructions for LLM flows. */\npublic final class Instructions implements RequestProcessor {\n public Instructions() {}\n\n @Override\n public Single processRequest(\n InvocationContext context, LlmRequest request) {\n if (!(context.agent() instanceof LlmAgent)) {\n return Single.error(\n new IllegalArgumentException(\n \"Agent in InvocationContext is not an instance of LlmAgent.\"));\n }\n LlmAgent agent = (LlmAgent) context.agent();\n ReadonlyContext readonlyContext = new ReadonlyContext(context);\n Single builderSingle = Single.just(request.toBuilder());\n if (agent.rootAgent() instanceof LlmAgent) {\n LlmAgent rootAgent = (LlmAgent) agent.rootAgent();\n builderSingle =\n builderSingle.flatMap(\n builder ->\n rootAgent\n .canonicalGlobalInstruction(readonlyContext)\n .flatMap(\n globalInstr -> {\n if (!globalInstr.isEmpty()) {\n return InstructionUtils.injectSessionState(context, globalInstr)\n .map(\n resolvedGlobalInstr ->\n builder.appendInstructions(\n ImmutableList.of(resolvedGlobalInstr)));\n }\n return Single.just(builder);\n }));\n }\n\n builderSingle =\n builderSingle.flatMap(\n builder ->\n agent\n .canonicalInstruction(readonlyContext)\n .flatMap(\n agentInstr -> {\n if (!agentInstr.isEmpty()) {\n return InstructionUtils.injectSessionState(context, agentInstr)\n .map(\n resolvedAgentInstr ->\n builder.appendInstructions(\n ImmutableList.of(resolvedAgentInstr)));\n }\n return Single.just(builder);\n }));\n\n return builderSingle.map(\n finalBuilder ->\n RequestProcessor.RequestProcessingResult.create(\n finalBuilder.build(), ImmutableList.of()));\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/sessions/BaseSessionService.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\nimport com.google.adk.events.Event;\nimport com.google.adk.events.EventActions;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport io.reactivex.rxjava3.core.Completable;\nimport io.reactivex.rxjava3.core.Maybe;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.List;\nimport java.util.Objects;\nimport java.util.Optional;\nimport java.util.concurrent.ConcurrentMap;\nimport javax.annotation.Nullable;\n\n/**\n * Defines the contract for managing {@link Session}s and their associated {@link Event}s. Provides\n * methods for creating, retrieving, listing, and deleting sessions, as well as listing and\n * appending events to a session. Implementations of this interface handle the underlying storage\n * and retrieval logic.\n */\npublic interface BaseSessionService {\n\n /**\n * Creates a new session with the specified parameters.\n *\n * @param appName The name of the application associated with the session.\n * @param userId The identifier for the user associated with the session.\n * @param state An optional map representing the initial state of the session. Can be null or\n * empty.\n * @param sessionId An optional client-provided identifier for the session. If empty or null, the\n * service should generate a unique ID.\n * @return The newly created {@link Session} instance.\n * @throws SessionException if creation fails.\n */\n Single createSession(\n String appName,\n String userId,\n @Nullable ConcurrentMap state,\n @Nullable String sessionId);\n\n /**\n * Creates a new session with the specified application name and user ID, using a default state\n * (null) and allowing the service to generate a unique session ID.\n *\n *

This is a shortcut for {@link #createSession(String, String, Map, String)} with null state\n * and a null session ID.\n *\n * @param appName The name of the application associated with the session.\n * @param userId The identifier for the user associated with the session.\n * @return The newly created {@link Session} instance.\n * @throws SessionException if creation fails.\n */\n default Single createSession(String appName, String userId) {\n return createSession(appName, userId, null, null);\n }\n\n /**\n * Retrieves a specific session, optionally filtering the events included.\n *\n * @param appName The name of the application.\n * @param userId The identifier of the user.\n * @param sessionId The unique identifier of the session to retrieve.\n * @param config Optional configuration to filter the events returned within the session (e.g.,\n * limit number of recent events, filter by timestamp). If empty, default retrieval behavior\n * is used (potentially all events or a service-defined limit).\n * @return An {@link Optional} containing the {@link Session} if found, otherwise {@link\n * Optional#empty()}.\n * @throws SessionException for retrieval errors other than not found.\n */\n Maybe getSession(\n String appName, String userId, String sessionId, Optional config);\n\n /**\n * Lists sessions associated with a specific application and user.\n *\n *

The {@link Session} objects in the response typically contain only metadata (like ID,\n * creation time) and not the full event list or state to optimize performance.\n *\n * @param appName The name of the application.\n * @param userId The identifier of the user whose sessions are to be listed.\n * @return A {@link ListSessionsResponse} containing a list of matching sessions.\n * @throws SessionException if listing fails.\n */\n Single listSessions(String appName, String userId);\n\n /**\n * Deletes a specific session.\n *\n * @param appName The name of the application.\n * @param userId The identifier of the user.\n * @param sessionId The unique identifier of the session to delete.\n * @throws SessionNotFoundException if the session doesn't exist.\n * @throws SessionException for other deletion errors.\n */\n Completable deleteSession(String appName, String userId, String sessionId);\n\n /**\n * Lists the events within a specific session. Supports pagination via the response object.\n *\n * @param appName The name of the application.\n * @param userId The identifier of the user.\n * @param sessionId The unique identifier of the session whose events are to be listed.\n * @return A {@link ListEventsResponse} containing a list of events and an optional token for\n * retrieving the next page.\n * @throws SessionNotFoundException if the session doesn't exist.\n * @throws SessionException for other listing errors.\n */\n Single listEvents(String appName, String userId, String sessionId);\n\n /**\n * Closes a session. This is currently a placeholder and may involve finalizing session state or\n * performing cleanup actions in future implementations. The default implementation does nothing.\n *\n * @param session The session object to close.\n */\n default Completable closeSession(Session session) {\n // Default implementation does nothing.\n // TODO: Determine whether we want to finalize the session here.\n return Completable.complete();\n }\n\n /**\n * Appends an event to an in-memory session object and updates the session's state based on the\n * event's state delta, if applicable.\n *\n *

This method primarily modifies the passed {@code session} object in memory. Persisting these\n * changes typically requires a separate call to an update/save method provided by the specific\n * service implementation, or might happen implicitly depending on the implementation's design.\n *\n *

If the event is marked as partial (e.g., {@code event.isPartial() == true}), it is returned\n * directly without modifying the session state or event list. State delta keys starting with\n * {@link State#TEMP_PREFIX} are ignored during state updates.\n *\n * @param session The {@link Session} object to which the event should be appended (will be\n * mutated).\n * @param event The {@link Event} to append.\n * @return The appended {@link Event} instance (or the original event if it was partial).\n * @throws NullPointerException if session or event is null.\n */\n @CanIgnoreReturnValue\n default Single appendEvent(Session session, Event event) {\n Objects.requireNonNull(session, \"session cannot be null\");\n Objects.requireNonNull(event, \"event cannot be null\");\n\n // If the event indicates it's partial or incomplete, don't process it yet.\n if (event.partial().orElse(false)) {\n return Single.just(event);\n }\n\n EventActions actions = event.actions();\n if (actions != null) {\n ConcurrentMap stateDelta = actions.stateDelta();\n if (stateDelta != null && !stateDelta.isEmpty()) {\n ConcurrentMap sessionState = session.state();\n if (sessionState != null) {\n stateDelta.forEach(\n (key, value) -> {\n if (!key.startsWith(State.TEMP_PREFIX)) {\n sessionState.put(key, value);\n }\n });\n }\n }\n }\n\n List sessionEvents = session.events();\n if (sessionEvents != null) {\n sessionEvents.add(event);\n }\n\n return Single.just(event);\n }\n}\n"], ["/adk-java/dev/src/main/java/com/google/adk/web/config/AdkWebCorsProperties.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.web.config;\n\nimport java.util.List;\nimport org.springframework.boot.context.properties.ConfigurationProperties;\n\n/**\n * Properties for configuring CORS in ADK Web. This class is used to load CORS settings from\n * application properties.\n */\n@ConfigurationProperties(prefix = \"adk.web.cors\")\npublic record AdkWebCorsProperties(\n String mapping,\n List origins,\n List methods,\n List headers,\n boolean allowCredentials,\n long maxAge) {\n\n public AdkWebCorsProperties {\n mapping = mapping != null ? mapping : \"/**\";\n origins = origins != null && !origins.isEmpty() ? origins : List.of();\n methods =\n methods != null && !methods.isEmpty()\n ? methods\n : List.of(\"GET\", \"POST\", \"PUT\", \"DELETE\", \"OPTIONS\");\n headers = headers != null && !headers.isEmpty() ? headers : List.of(\"*\");\n maxAge = maxAge > 0 ? maxAge : 3600;\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/JsonBaseModel.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk;\n\nimport com.fasterxml.jackson.annotation.JsonInclude;\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.fasterxml.jackson.databind.DeserializationFeature;\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.fasterxml.jackson.databind.PropertyNamingStrategies;\nimport com.fasterxml.jackson.datatype.jdk8.Jdk8Module;\nimport com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;\n\n/** The base class for the types that needs JSON serialization/deserialization capability. */\npublic abstract class JsonBaseModel {\n\n private static final ObjectMapper objectMapper = new ObjectMapper();\n\n static {\n objectMapper\n .setSerializationInclusion(JsonInclude.Include.NON_ABSENT)\n .setPropertyNamingStrategy(PropertyNamingStrategies.LOWER_CAMEL_CASE)\n .registerModule(new Jdk8Module())\n .registerModule(new JavaTimeModule()) // TODO: echo sec module replace, locale\n .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);\n }\n\n /** Serializes an object to a Json string. */\n protected static String toJsonString(Object object) {\n try {\n return objectMapper.writeValueAsString(object);\n } catch (JsonProcessingException e) {\n throw new IllegalStateException(e);\n }\n }\n\n public static ObjectMapper getMapper() {\n return JsonBaseModel.objectMapper;\n }\n\n public String toJson() {\n return toJsonString(this);\n }\n\n /** Serializes an object to a JsonNode. */\n protected static JsonNode toJsonNode(Object object) {\n return objectMapper.valueToTree(object);\n }\n\n /** Deserializes a Json string to an object of the given type. */\n public static T fromJsonString(String jsonString, Class clazz) {\n try {\n return objectMapper.readValue(jsonString, clazz);\n } catch (JsonProcessingException e) {\n throw new IllegalStateException(e);\n }\n }\n\n /** Deserializes a JsonNode to an object of the given type. */\n public static T fromJsonNode(JsonNode jsonNode, Class clazz) {\n try {\n return objectMapper.treeToValue(jsonNode, clazz);\n } catch (JsonProcessingException e) {\n throw new IllegalStateException(e);\n }\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/agents/ReadonlyContext.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.agents;\n\nimport com.google.adk.events.Event;\nimport com.google.genai.types.Content;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\n\n/** Provides read-only access to the context of an agent run. */\npublic class ReadonlyContext {\n\n protected final InvocationContext invocationContext;\n private List eventsView;\n private Map stateView;\n\n public ReadonlyContext(InvocationContext invocationContext) {\n this.invocationContext = invocationContext;\n }\n\n /** Returns the user content that initiated this invocation. */\n public Optional userContent() {\n return invocationContext.userContent();\n }\n\n /** Returns the ID of the current invocation. */\n public String invocationId() {\n return invocationContext.invocationId();\n }\n\n /** Returns the branch of the current invocation, if present. */\n public Optional branch() {\n return invocationContext.branch();\n }\n\n /** Returns the name of the agent currently running. */\n public String agentName() {\n return invocationContext.agent().name();\n }\n\n /** Returns the session ID. */\n public String sessionId() {\n return invocationContext.session().id();\n }\n\n /**\n * Returns an unmodifiable view of the events of the session.\n *\n *

Warning: This is a live view, not a snapshot.\n */\n public List events() {\n if (eventsView == null) {\n eventsView = Collections.unmodifiableList(invocationContext.session().events());\n }\n return eventsView;\n }\n\n /**\n * Returns an unmodifiable view of the state of the session.\n *\n *

Warning: This is a live view, not a snapshot.\n */\n public Map state() {\n if (stateView == null) {\n stateView = Collections.unmodifiableMap(invocationContext.session().state());\n }\n return stateView;\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/memory/BaseMemoryService.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.memory;\n\nimport com.google.adk.sessions.Session;\nimport io.reactivex.rxjava3.core.Completable;\nimport io.reactivex.rxjava3.core.Single;\n\n/**\n * Base contract for memory services.\n *\n *

The service provides functionalities to ingest sessions into memory so that the memory can be\n * used for user queries.\n */\npublic interface BaseMemoryService {\n\n /**\n * Adds a session to the memory service.\n *\n *

A session may be added multiple times during its lifetime.\n *\n * @param session The session to add.\n */\n Completable addSessionToMemory(Session session);\n\n /**\n * Searches for sessions that match the query asynchronously.\n *\n * @param appName The name of the application.\n * @param userId The id of the user.\n * @param query The query to search for.\n * @return A {@link SearchMemoryResponse} containing the matching memories.\n */\n Single searchMemory(String appName, String userId, String query);\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/models/BaseLlm.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.models;\n\nimport io.reactivex.rxjava3.core.Flowable;\n\n/**\n * Abstract base class for Large Language Models (LLMs).\n *\n *

Provides a common interface for interacting with different LLMs.\n */\npublic abstract class BaseLlm {\n\n /** The name of the LLM model, e.g. gemini-1.5-flash or gemini-1.5-flash-001. */\n private final String model;\n\n public BaseLlm(String model) {\n this.model = model;\n }\n\n /**\n * Returns the name of the LLM model.\n *\n * @return The name of the LLM model.\n */\n public String model() {\n return model;\n }\n\n /**\n * Generates one content from the given LLM request and tools.\n *\n * @param llmRequest The LLM request containing the input prompt and parameters.\n * @param stream A boolean flag indicating whether to stream the response.\n * @return A Flowable of LlmResponses. For non-streaming calls, it will only yield one\n * LlmResponse. For streaming calls, it may yield more than one LlmResponse, but all yielded\n * LlmResponses should be treated as one content by merging their parts.\n */\n public abstract Flowable generateContent(LlmRequest llmRequest, boolean stream);\n\n /** Creates a live connection to the LLM. */\n public abstract BaseLlmConnection connect(LlmRequest llmRequest);\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/sessions/Session.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.databind.annotation.JsonDeserialize;\nimport com.google.adk.JsonBaseModel;\nimport com.google.adk.events.Event;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport java.time.Duration;\nimport java.time.Instant;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentMap;\n\n/** A {@link Session} object that encapsulates the {@link State} and {@link Event}s of a session. */\n@JsonDeserialize(builder = Session.Builder.class)\npublic final class Session extends JsonBaseModel {\n private final String id;\n\n private final String appName;\n\n private final String userId;\n\n private final State state;\n\n private final List events;\n\n private Instant lastUpdateTime;\n\n public static Builder builder(String id) {\n return new Builder(id);\n }\n\n /** Builder for {@link Session}. */\n public static final class Builder {\n private String id;\n private String appName;\n private String userId;\n private State state = new State(new ConcurrentHashMap<>());\n private List events = new ArrayList<>();\n private Instant lastUpdateTime = Instant.EPOCH;\n\n public Builder(String id) {\n this.id = id;\n }\n\n @JsonCreator\n private Builder() {}\n\n @CanIgnoreReturnValue\n @JsonProperty(\"id\")\n public Builder id(String id) {\n this.id = id;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder state(State state) {\n this.state = state;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"state\")\n public Builder state(ConcurrentMap state) {\n this.state = new State(state);\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"appName\")\n public Builder appName(String appName) {\n this.appName = appName;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"userId\")\n public Builder userId(String userId) {\n this.userId = userId;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"events\")\n public Builder events(List events) {\n this.events = events;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder lastUpdateTime(Instant lastUpdateTime) {\n this.lastUpdateTime = lastUpdateTime;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"lastUpdateTime\")\n public Builder lastUpdateTimeSeconds(double seconds) {\n long secs = (long) seconds;\n // Convert fractional part to nanoseconds\n long nanos = (long) ((seconds - secs) * Duration.ofSeconds(1).toNanos());\n this.lastUpdateTime = Instant.ofEpochSecond(secs, nanos);\n return this;\n }\n\n public Session build() {\n if (id == null) {\n throw new IllegalStateException(\"Session id is null\");\n }\n return new Session(appName, userId, id, state, events, lastUpdateTime);\n }\n }\n\n @JsonProperty(\"id\")\n public String id() {\n return id;\n }\n\n @JsonProperty(\"state\")\n public ConcurrentMap state() {\n return state;\n }\n\n @JsonProperty(\"events\")\n public List events() {\n return events;\n }\n\n @JsonProperty(\"appName\")\n public String appName() {\n return appName;\n }\n\n @JsonProperty(\"userId\")\n public String userId() {\n return userId;\n }\n\n public void lastUpdateTime(Instant lastUpdateTime) {\n this.lastUpdateTime = lastUpdateTime;\n }\n\n public Instant lastUpdateTime() {\n return lastUpdateTime;\n }\n\n @JsonProperty(\"lastUpdateTime\")\n public double getLastUpdateTimeAsDouble() {\n if (lastUpdateTime == null) {\n return 0.0;\n }\n long seconds = lastUpdateTime.getEpochSecond();\n int nanos = lastUpdateTime.getNano();\n return seconds + nanos / (double) Duration.ofSeconds(1).toNanos();\n }\n\n @Override\n public String toString() {\n return toJson();\n }\n\n public static Session fromJson(String json) {\n return fromJsonString(json, Session.class);\n }\n\n private Session(\n String appName,\n String userId,\n String id,\n State state,\n List events,\n Instant lastUpdateTime) {\n this.id = id;\n this.appName = appName;\n this.userId = userId;\n this.state = state;\n this.events = events;\n this.lastUpdateTime = lastUpdateTime;\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/artifacts/BaseArtifactService.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.artifacts;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.genai.types.Part;\nimport io.reactivex.rxjava3.core.Completable;\nimport io.reactivex.rxjava3.core.Maybe;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.Optional;\n\n/** Base interface for artifact services. */\npublic interface BaseArtifactService {\n\n /**\n * Saves an artifact.\n *\n * @param appName the app name\n * @param userId the user ID\n * @param sessionId the session ID\n * @param filename the filename\n * @param artifact the artifact\n * @return the revision ID (version) of the saved artifact.\n */\n Single saveArtifact(\n String appName, String userId, String sessionId, String filename, Part artifact);\n\n /**\n * Gets an artifact.\n *\n * @param appName the app name\n * @param userId the user ID\n * @param sessionId the session ID\n * @param filename the filename\n * @param version Optional version number. If null, loads the latest version.\n * @return the artifact or empty if not found\n */\n Maybe loadArtifact(\n String appName, String userId, String sessionId, String filename, Optional version);\n\n /**\n * Lists all the artifact filenames within a session.\n *\n * @param appName the app name\n * @param userId the user ID\n * @param sessionId the session ID\n * @return the list artifact response containing filenames\n */\n Single listArtifactKeys(String appName, String userId, String sessionId);\n\n /**\n * Deletes an artifact.\n *\n * @param appName the app name\n * @param userId the user ID\n * @param sessionId the session ID\n * @param filename the filename\n */\n Completable deleteArtifact(String appName, String userId, String sessionId, String filename);\n\n /**\n * Lists all the versions (as revision IDs) of an artifact.\n *\n * @param appName the app name\n * @param userId the user ID\n * @param sessionId the session ID\n * @param filename the artifact filename\n * @return A list of integer version numbers.\n */\n Single> listVersions(\n String appName, String userId, String sessionId, String filename);\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/agents/LiveRequestQueue.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.agents;\n\nimport com.google.genai.types.Blob;\nimport com.google.genai.types.Content;\nimport io.reactivex.rxjava3.core.Flowable;\nimport io.reactivex.rxjava3.processors.FlowableProcessor;\nimport io.reactivex.rxjava3.processors.MulticastProcessor;\n\n/** A queue of live requests to be sent to the model. */\npublic final class LiveRequestQueue {\n private final FlowableProcessor processor;\n\n public LiveRequestQueue() {\n MulticastProcessor processor = MulticastProcessor.create();\n processor.start();\n this.processor = processor.toSerialized();\n }\n\n public void close() {\n processor.onNext(LiveRequest.builder().close(true).build());\n processor.onComplete();\n }\n\n public void content(Content content) {\n processor.onNext(LiveRequest.builder().content(content).build());\n }\n\n public void realtime(Blob blob) {\n processor.onNext(LiveRequest.builder().blob(blob).build());\n }\n\n public void send(LiveRequest request) {\n processor.onNext(request);\n if (request.shouldClose()) {\n processor.onComplete();\n }\n }\n\n public Flowable get() {\n return processor;\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/llmflows/SingleFlow.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows.llmflows;\n\nimport com.google.common.collect.ImmutableList;\nimport java.util.List;\nimport java.util.Optional;\n\n/** Basic LLM flow with fixed request processors and no response post-processing. */\npublic class SingleFlow extends BaseLlmFlow {\n\n protected static final ImmutableList REQUEST_PROCESSORS =\n ImmutableList.of(\n new Basic(), new Instructions(), new Identity(), new Contents(), new Examples());\n\n protected static final ImmutableList RESPONSE_PROCESSORS = ImmutableList.of();\n\n public SingleFlow() {\n this(/* maxSteps= */ Optional.empty());\n }\n\n public SingleFlow(Optional maxSteps) {\n this(REQUEST_PROCESSORS, RESPONSE_PROCESSORS, maxSteps);\n }\n\n protected SingleFlow(\n List requestProcessors,\n List responseProcessors,\n Optional maxSteps) {\n super(requestProcessors, responseProcessors, maxSteps);\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/sessions/State.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\nimport java.util.Collection;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.Objects;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentMap;\n\n/** A {@link State} object that also keeps track of the changes to the state. */\n@SuppressWarnings(\"ShouldNotSubclass\")\npublic final class State implements ConcurrentMap {\n\n public static final String APP_PREFIX = \"app:\";\n public static final String USER_PREFIX = \"user:\";\n public static final String TEMP_PREFIX = \"temp:\";\n\n // Sentinel object to mark removed entries in the delta map\n private static final Object REMOVED = new Object();\n\n private final ConcurrentMap state;\n private final ConcurrentMap delta;\n\n public State(ConcurrentMap state) {\n this(state, new ConcurrentHashMap<>());\n }\n\n public State(ConcurrentMap state, ConcurrentMap delta) {\n this.state = Objects.requireNonNull(state);\n this.delta = delta;\n }\n\n @Override\n public void clear() {\n state.clear();\n }\n\n @Override\n public boolean containsKey(Object key) {\n return state.containsKey(key);\n }\n\n @Override\n public boolean containsValue(Object value) {\n return state.containsValue(value);\n }\n\n @Override\n public Set> entrySet() {\n return state.entrySet();\n }\n\n @Override\n public boolean equals(Object o) {\n if (o == this) {\n return true;\n }\n if (!(o instanceof State other)) {\n return false;\n }\n return state.equals(other.state);\n }\n\n @Override\n public Object get(Object key) {\n return state.get(key);\n }\n\n @Override\n public int hashCode() {\n return state.hashCode();\n }\n\n @Override\n public boolean isEmpty() {\n return state.isEmpty();\n }\n\n @Override\n public Set keySet() {\n return state.keySet();\n }\n\n @Override\n public Object put(String key, Object value) {\n Object oldValue = state.put(key, value);\n delta.put(key, value);\n return oldValue;\n }\n\n @Override\n public Object putIfAbsent(String key, Object value) {\n Object existingValue = state.putIfAbsent(key, value);\n if (existingValue == null) {\n delta.put(key, value);\n }\n return existingValue;\n }\n\n @Override\n public void putAll(Map m) {\n state.putAll(m);\n delta.putAll(m);\n }\n\n @Override\n public Object remove(Object key) {\n if (state.containsKey(key)) {\n delta.put((String) key, REMOVED);\n }\n return state.remove(key);\n }\n\n @Override\n public boolean remove(Object key, Object value) {\n boolean removed = state.remove(key, value);\n if (removed) {\n delta.put((String) key, REMOVED);\n }\n return removed;\n }\n\n @Override\n public boolean replace(String key, Object oldValue, Object newValue) {\n boolean replaced = state.replace(key, oldValue, newValue);\n if (replaced) {\n delta.put(key, newValue);\n }\n return replaced;\n }\n\n @Override\n public Object replace(String key, Object value) {\n Object oldValue = state.replace(key, value);\n if (oldValue != null) {\n delta.put(key, value);\n }\n return oldValue;\n }\n\n @Override\n public int size() {\n return state.size();\n }\n\n @Override\n public Collection values() {\n return state.values();\n }\n\n public boolean hasDelta() {\n return !delta.isEmpty();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/ExitLoopTool.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools;\n\n/** Exits the loop. */\npublic final class ExitLoopTool {\n public static void exitLoop(ToolContext toolContext) {\n // Exits the loop.\n // Call this function only when you are instructed to do so.\n toolContext.setActions(toolContext.actions().toBuilder().escalate(true).build());\n }\n\n private ExitLoopTool() {}\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/memory/SearchMemoryResponse.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.memory;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\nimport java.util.List;\n\n/** Represents the response from a memory search. */\n@AutoValue\npublic abstract class SearchMemoryResponse {\n\n /** Returns a list of memory entries that relate to the search query. */\n public abstract ImmutableList memories();\n\n /** Creates a new builder for {@link SearchMemoryResponse}. */\n public static Builder builder() {\n return new AutoValue_SearchMemoryResponse.Builder().setMemories(ImmutableList.of());\n }\n\n /** Builder for {@link SearchMemoryResponse}. */\n @AutoValue.Builder\n public abstract static class Builder {\n\n abstract Builder setMemories(ImmutableList memories);\n\n /** Sets the list of memory entries using a list. */\n public Builder setMemories(List memories) {\n return setMemories(ImmutableList.copyOf(memories));\n }\n\n /** Builds the immutable {@link SearchMemoryResponse} object. */\n public abstract SearchMemoryResponse build();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/network/HttpApiResponse.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.network;\n\nimport com.google.genai.errors.ApiException;\nimport com.google.genai.errors.ClientException;\nimport com.google.genai.errors.ServerException;\nimport java.io.IOException;\nimport okhttp3.Response;\nimport okhttp3.ResponseBody;\n\n/** Wraps a real HTTP response to expose the methods needed by the GenAI SDK. */\npublic final class HttpApiResponse extends ApiResponse {\n\n private final Response response;\n\n /** Constructs a HttpApiResponse instance with the response. */\n public HttpApiResponse(Response response) {\n throwFromResponse(response);\n this.response = response;\n }\n\n /** Returns the ResponseBody from the response. */\n @Override\n public ResponseBody getEntity() {\n return response.body();\n }\n\n /**\n * Throws an ApiException from the response if the response is not a OK status. This method is\n * adapted to work with OkHttp's Response.\n *\n * @param response The response from the API call.\n */\n private void throwFromResponse(Response response) {\n if (response.isSuccessful()) {\n return;\n }\n int code = response.code();\n String status = response.message();\n String message = getErrorMessageFromResponse(response);\n if (code >= 400 && code < 500) { // Client errors.\n throw new ClientException(code, status, message);\n } else if (code >= 500 && code < 600) { // Server errors.\n throw new ServerException(code, status, message);\n } else {\n throw new ApiException(code, status, message);\n }\n }\n\n private String getErrorMessageFromResponse(Response response) {\n try {\n if (response.body() != null) {\n return response.body().string(); // Consume only once.\n }\n } catch (IOException e) {\n // Log the error. Return a generic message to avoid masking original exception.\n return \"Error reading response body\";\n }\n return \"\";\n }\n\n /** Closes the Http response. */\n @Override\n public void close() {\n response.close();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/agents/CallbackUtil.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.agents;\n\nimport com.google.adk.agents.Callbacks.AfterAgentCallback;\nimport com.google.adk.agents.Callbacks.AfterAgentCallbackBase;\nimport com.google.adk.agents.Callbacks.AfterAgentCallbackSync;\nimport com.google.adk.agents.Callbacks.BeforeAgentCallback;\nimport com.google.adk.agents.Callbacks.BeforeAgentCallbackBase;\nimport com.google.adk.agents.Callbacks.BeforeAgentCallbackSync;\nimport com.google.common.collect.ImmutableList;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport io.reactivex.rxjava3.core.Maybe;\nimport java.util.List;\nimport org.jspecify.annotations.Nullable;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/** Utility methods for normalizing agent callbacks. */\npublic final class CallbackUtil {\n private static final Logger logger = LoggerFactory.getLogger(CallbackUtil.class);\n\n /**\n * Normalizes before-agent callbacks.\n *\n * @param beforeAgentCallback Callback list (sync or async).\n * @return normalized async callbacks, or null if input is null.\n */\n @CanIgnoreReturnValue\n public static @Nullable ImmutableList getBeforeAgentCallbacks(\n List beforeAgentCallback) {\n if (beforeAgentCallback == null) {\n return null;\n } else if (beforeAgentCallback.isEmpty()) {\n return ImmutableList.of();\n } else {\n ImmutableList.Builder builder = ImmutableList.builder();\n for (BeforeAgentCallbackBase callback : beforeAgentCallback) {\n if (callback instanceof BeforeAgentCallback beforeAgentCallbackInstance) {\n builder.add(beforeAgentCallbackInstance);\n } else if (callback instanceof BeforeAgentCallbackSync beforeAgentCallbackSyncInstance) {\n builder.add(\n (BeforeAgentCallback)\n (callbackContext) ->\n Maybe.fromOptional(beforeAgentCallbackSyncInstance.call(callbackContext)));\n } else {\n logger.warn(\n \"Invalid beforeAgentCallback callback type: %s. Ignoring this callback.\",\n callback.getClass().getName());\n }\n }\n return builder.build();\n }\n }\n\n /**\n * Normalizes after-agent callbacks.\n *\n * @param afterAgentCallback Callback list (sync or async).\n * @return normalized async callbacks, or null if input is null.\n */\n @CanIgnoreReturnValue\n public static @Nullable ImmutableList getAfterAgentCallbacks(\n List afterAgentCallback) {\n if (afterAgentCallback == null) {\n return null;\n } else if (afterAgentCallback.isEmpty()) {\n return ImmutableList.of();\n } else {\n ImmutableList.Builder builder = ImmutableList.builder();\n for (AfterAgentCallbackBase callback : afterAgentCallback) {\n if (callback instanceof AfterAgentCallback afterAgentCallbackInstance) {\n builder.add(afterAgentCallbackInstance);\n } else if (callback instanceof AfterAgentCallbackSync afterAgentCallbackSyncInstance) {\n builder.add(\n (AfterAgentCallback)\n (callbackContext) ->\n Maybe.fromOptional(afterAgentCallbackSyncInstance.call(callbackContext)));\n } else {\n logger.warn(\n \"Invalid afterAgentCallback callback type: %s. Ignoring this callback.\",\n callback.getClass().getName());\n }\n }\n return builder.build();\n }\n }\n\n private CallbackUtil() {}\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/models/Model.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.models;\n\nimport com.google.auto.value.AutoValue;\nimport java.util.Optional;\n\n/** Represents a model by name or instance. */\n@AutoValue\npublic abstract class Model {\n\n public abstract Optional modelName();\n\n public abstract Optional model();\n\n public static Builder builder() {\n return new AutoValue_Model.Builder();\n }\n\n public abstract Builder toBuilder();\n\n /** Builder for {@link Model}. */\n @AutoValue.Builder\n public abstract static class Builder {\n\n public abstract Builder modelName(String modelName);\n\n public abstract Builder model(BaseLlm model);\n\n public abstract Model build();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/events/EventStream.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.events;\n\nimport java.util.Iterator;\nimport java.util.NoSuchElementException;\nimport java.util.function.Supplier;\n\n/** Iterable stream of {@link Event} objects. */\npublic class EventStream implements Iterable {\n\n private final Supplier eventSupplier;\n\n /** Constructs a new event stream. */\n public EventStream(Supplier eventSupplier) {\n this.eventSupplier = eventSupplier;\n }\n\n /** Returns an iterator that fetches events lazily. */\n @Override\n public Iterator iterator() {\n return new EventIterator();\n }\n\n /** Iterator that returns events from the supplier until it returns {@code null}. */\n private class EventIterator implements Iterator {\n private Event nextEvent = null;\n private boolean finished = false;\n\n /** Returns {@code true} if another event is available. */\n @Override\n public boolean hasNext() {\n if (finished) {\n return false;\n }\n if (nextEvent == null) {\n nextEvent = eventSupplier.get();\n finished = (nextEvent == null);\n }\n return !finished;\n }\n\n /**\n * Returns the next event.\n *\n * @throws NoSuchElementException if no more events are available.\n */\n @Override\n public Event next() {\n if (!hasNext()) {\n throw new NoSuchElementException(\"No more events.\");\n }\n Event currentEvent = nextEvent;\n nextEvent = null;\n return currentEvent;\n }\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/artifacts/ListArtifactVersionsResponse.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.artifacts;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\nimport com.google.genai.types.Part;\nimport java.util.List;\n\n/** Response for listing artifact versions. */\n@AutoValue\npublic abstract class ListArtifactVersionsResponse {\n\n public abstract ImmutableList versions();\n\n /** Builder for {@link ListArtifactVersionsResponse}. */\n @AutoValue.Builder\n public abstract static class Builder {\n public abstract Builder versions(List versions);\n\n public abstract ListArtifactVersionsResponse build();\n }\n\n public static Builder builder() {\n return new AutoValue_ListArtifactVersionsResponse.Builder();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/sessions/ListEventsResponse.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\nimport com.google.adk.events.Event;\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\nimport java.util.List;\nimport java.util.Optional;\n\n/** Response for listing events. */\n@AutoValue\npublic abstract class ListEventsResponse {\n\n public abstract ImmutableList events();\n\n public abstract Optional nextPageToken();\n\n /** Builder for {@link ListEventsResponse}. */\n @AutoValue.Builder\n public abstract static class Builder {\n\n public abstract Builder events(List events);\n\n public abstract Builder nextPageToken(String nextPageToken);\n\n public abstract ListEventsResponse build();\n }\n\n public static Builder builder() {\n return new AutoValue_ListEventsResponse.Builder().events(ImmutableList.of());\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/memory/MemoryEntry.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.memory;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.genai.types.Content;\nimport java.time.Instant;\nimport javax.annotation.Nullable;\n\n/** Represents one memory entry. */\n@AutoValue\npublic abstract class MemoryEntry {\n\n /** Returns the main content of the memory. */\n public abstract Content content();\n\n /** Returns the author of the memory, or null if not set. */\n @Nullable\n public abstract String author();\n\n /**\n * Returns the timestamp when the original content of this memory happened, or null if not set.\n *\n *

This string will be forwarded to LLM. Preferred format is ISO 8601 format\n */\n @Nullable\n public abstract String timestamp();\n\n /** Returns a new builder for creating a {@link MemoryEntry}. */\n public static Builder builder() {\n return new AutoValue_MemoryEntry.Builder();\n }\n\n /**\n * Creates a new builder with a copy of this entry's values.\n *\n * @return a new {@link Builder} instance.\n */\n public abstract Builder toBuilder();\n\n /** Builder for {@link MemoryEntry}. */\n @AutoValue.Builder\n public abstract static class Builder {\n\n /**\n * Sets the main content of the memory.\n *\n *

This is a required field.\n */\n public abstract Builder setContent(Content content);\n\n /** Sets the author of the memory. */\n public abstract Builder setAuthor(@Nullable String author);\n\n /** Sets the timestamp when the original content of this memory happened. */\n public abstract Builder setTimestamp(@Nullable String timestamp);\n\n /**\n * A convenience method to set the timestamp from an {@link Instant} object, formatted as an ISO\n * 8601 string.\n *\n * @param instant The timestamp as an Instant object.\n */\n public Builder setTimestamp(Instant instant) {\n return setTimestamp(instant.toString());\n }\n\n /** Builds the immutable {@link MemoryEntry} object. */\n public abstract MemoryEntry build();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/models/BaseLlmConnection.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.models;\n\nimport com.google.genai.types.Blob;\nimport com.google.genai.types.Content;\nimport io.reactivex.rxjava3.core.Completable;\nimport io.reactivex.rxjava3.core.Flowable;\nimport java.util.List;\n\n/** The base class for a live model connection. */\npublic interface BaseLlmConnection {\n\n /**\n * Sends the conversation history to the model.\n *\n *

You call this method right after setting up the model connection. The model will respond if\n * the last content is from user, otherwise it will wait for new user input before responding.\n */\n Completable sendHistory(List history);\n\n /**\n * Sends a user content to the model.\n *\n *

The model will respond immediately upon receiving the content. If you send function\n * responses, all parts in the content should be function responses.\n */\n Completable sendContent(Content content);\n\n /**\n * Sends a chunk of audio or a frame of video to the model in realtime.\n *\n *

The model may not respond immediately upon receiving the blob. It will do voice activity\n * detection and decide when to respond.\n */\n Completable sendRealtime(Blob blob);\n\n /** Receives the model responses. */\n Flowable receive();\n\n /** Closes the connection. */\n void close();\n\n /** Closes the connection with an error. */\n void close(Throwable throwable);\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/models/VertexCredentials.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.models;\n\nimport com.google.auth.oauth2.GoogleCredentials;\nimport com.google.auto.value.AutoValue;\nimport java.util.Optional;\nimport javax.annotation.Nullable;\n\n/** Credentials for accessing Gemini models through Vertex. */\n@AutoValue\npublic abstract class VertexCredentials {\n\n public abstract Optional project();\n\n public abstract Optional location();\n\n public abstract Optional credentials();\n\n public static Builder builder() {\n return new AutoValue_VertexCredentials.Builder();\n }\n\n /** Builder for {@link VertexCredentials}. */\n @AutoValue.Builder\n public abstract static class Builder {\n public abstract Builder setProject(Optional value);\n\n public abstract Builder setProject(@Nullable String value);\n\n public abstract Builder setLocation(Optional value);\n\n public abstract Builder setLocation(@Nullable String value);\n\n public abstract Builder setCredentials(Optional value);\n\n public abstract Builder setCredentials(@Nullable GoogleCredentials value);\n\n public abstract VertexCredentials build();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/runner/InMemoryRunner.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.runner;\n\nimport com.google.adk.agents.BaseAgent;\nimport com.google.adk.artifacts.InMemoryArtifactService;\nimport com.google.adk.sessions.InMemorySessionService;\n\n/** The class for the in-memory GenAi runner, using in-memory artifact and session services. */\npublic class InMemoryRunner extends Runner {\n\n public InMemoryRunner(BaseAgent agent) {\n // TODO: Change the default appName to InMemoryRunner to align with adk python.\n // Check the dev UI in case we break something there.\n this(agent, /* appName= */ agent.name());\n }\n\n public InMemoryRunner(BaseAgent agent, String appName) {\n super(agent, appName, new InMemoryArtifactService(), new InMemorySessionService());\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/llmflows/ResponseProcessor.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows.llmflows;\n\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.events.Event;\nimport com.google.adk.models.LlmResponse;\nimport com.google.auto.value.AutoValue;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.Optional;\n\npublic interface ResponseProcessor {\n\n @AutoValue\n public abstract static class ResponseProcessingResult {\n public abstract LlmResponse updatedResponse();\n\n public abstract Iterable events();\n\n public abstract Optional transferToAgent();\n\n public static ResponseProcessingResult create(\n LlmResponse updatedResponse, Iterable events, Optional transferToAgent) {\n return new AutoValue_ResponseProcessor_ResponseProcessingResult(\n updatedResponse, events, transferToAgent);\n }\n }\n\n /**\n * Process the LLM response as part of the post-processing stage.\n *\n * @param context the invocation context.\n * @param response the LLM response to process.\n * @return a list of events generated during processing (if any).\n */\n Single processResponse(InvocationContext context, LlmResponse response);\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/sessions/GetSessionConfig.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\nimport com.google.auto.value.AutoValue;\nimport java.time.Instant;\nimport java.util.Optional;\n\n/** Configuration for getting a session. */\n@AutoValue\npublic abstract class GetSessionConfig {\n\n public abstract Optional numRecentEvents();\n\n public abstract Optional afterTimestamp();\n\n /** Builder for {@link GetSessionConfig}. */\n @AutoValue.Builder\n public abstract static class Builder {\n\n public abstract Builder numRecentEvents(int numRecentEvents);\n\n public abstract Builder afterTimestamp(Instant afterTimestamp);\n\n public abstract GetSessionConfig build();\n }\n\n public static Builder builder() {\n return new AutoValue_GetSessionConfig.Builder();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/sessions/SessionException.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\n/** Represents a general error that occurred during session management operations. */\npublic class SessionException extends RuntimeException {\n\n public SessionException(String message) {\n super(message);\n }\n\n public SessionException(String message, Throwable cause) {\n super(message, cause);\n }\n\n public SessionException(Throwable cause) {\n super(cause);\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/sessions/ListSessionsResponse.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\nimport static com.google.common.collect.ImmutableList.toImmutableList;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\nimport java.util.List;\n\n/** Response for listing sessions. */\n@AutoValue\npublic abstract class ListSessionsResponse {\n\n public abstract ImmutableList sessions();\n\n public List sessionIds() {\n return sessions().stream().map(Session::id).collect(toImmutableList());\n }\n\n /** Builder for {@link ListSessionsResponse}. */\n @AutoValue.Builder\n public abstract static class Builder {\n\n public abstract Builder sessions(List sessions);\n\n public abstract ListSessionsResponse build();\n }\n\n public static Builder builder() {\n return new AutoValue_ListSessionsResponse.Builder().sessions(ImmutableList.of());\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/sessions/SessionNotFoundException.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\n/** Indicates that a requested session could not be found. */\npublic class SessionNotFoundException extends SessionException {\n\n public SessionNotFoundException(String message) {\n super(message);\n }\n\n public SessionNotFoundException(String message, Throwable cause) {\n super(message, cause);\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/ToolPredicate.java", "package com.google.adk.tools;\n\nimport com.google.adk.agents.ReadonlyContext;\nimport java.util.Optional;\n\n/**\n * Functional interface to decide whether a tool should be exposed to the LLM based on the current\n * context.\n */\n@FunctionalInterface\npublic interface ToolPredicate {\n /**\n * Decides if the given tool is selected.\n *\n * @param tool The tool to check.\n * @param readonlyContext The current context.\n * @return true if the tool should be selected, false otherwise.\n */\n boolean test(BaseTool tool, Optional readonlyContext);\n}\n"], ["/adk-java/dev/src/main/java/com/google/adk/web/config/AgentLoadingProperties.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.web.config;\n\nimport org.springframework.boot.context.properties.ConfigurationProperties;\nimport org.springframework.stereotype.Component;\n\n/** Properties for loading agents. */\n@Component\n@ConfigurationProperties(prefix = \"adk.agents\")\npublic class AgentLoadingProperties {\n private String sourceDir = \"src/main/java\";\n private String compileClasspath;\n\n public String getSourceDir() {\n return sourceDir;\n }\n\n public void setSourceDir(String sourceDir) {\n this.sourceDir = sourceDir;\n }\n\n public String getCompileClasspath() {\n return compileClasspath;\n }\n\n public void setCompileClasspath(String compileClasspath) {\n this.compileClasspath = compileClasspath;\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/BaseFlow.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows;\n\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.events.Event;\nimport io.reactivex.rxjava3.core.Flowable;\n\n/** Interface for the execution flows to run a group of agents. */\npublic interface BaseFlow {\n\n /**\n * Run this flow.\n *\n *

To implement this method, the flow should follow the below requirements:\n *\n *

    \n *
  1. 1. `session` should be treated as immutable, DO NOT change it.\n *
  2. 2. The caller who trigger the flow is responsible for updating the session as the events\n * being generated. The subclass implementation will assume session is updated after each\n * yield event statement.\n *
  3. 3. A flow may spawn sub-agent flows depending on the agent definition.\n *
\n */\n Flowable run(InvocationContext invocationContext);\n\n default Flowable runLive(InvocationContext invocationContext) {\n throw new UnsupportedOperationException(\"Not implemented\");\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/llmflows/RequestProcessor.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows.llmflows;\n\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.events.Event;\nimport com.google.adk.models.LlmRequest;\nimport com.google.auto.value.AutoValue;\nimport io.reactivex.rxjava3.core.Single;\n\npublic interface RequestProcessor {\n\n @AutoValue\n public abstract static class RequestProcessingResult {\n public abstract LlmRequest updatedRequest();\n\n public abstract Iterable events();\n\n public static RequestProcessingResult create(\n LlmRequest updatedRequest, Iterable events) {\n return new AutoValue_RequestProcessor_RequestProcessingResult(updatedRequest, events);\n }\n }\n\n /**\n * Process the LLM request as part of the pre-processing stage.\n *\n * @param context the invocation context.\n * @param request the LLM request to process.\n * @return a list of events generated during processing (if any).\n */\n Single processRequest(InvocationContext context, LlmRequest request);\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/exceptions/LlmCallsLimitExceededException.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.google.adk.exceptions;\n\n/** An error indicating that the limit for calls to the LLM has been exceeded. */\npublic final class LlmCallsLimitExceededException extends Exception {\n\n public LlmCallsLimitExceededException(String message) {\n super(message);\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/utils/Pairs.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.utils;\n\nimport com.google.common.collect.ImmutableMap;\nimport java.util.concurrent.ConcurrentHashMap;\n\n/** Utility class for creating ConcurrentHashMaps. */\npublic final class Pairs {\n\n private Pairs() {}\n\n /**\n * Returns a new, empty {@code ConcurrentHashMap}.\n *\n * @param the {@code ConcurrentHashMap}'s key type\n * @param the {@code ConcurrentHashMap}'s value type\n * @return an empty {@code ConcurrentHashMap}\n */\n public static ConcurrentHashMap of() {\n return new ConcurrentHashMap<>();\n }\n\n /**\n * Returns a new {@code ConcurrentHashMap} containing a single mapping.\n *\n * @param the {@code ConcurrentHashMap}'s key type\n * @param the {@code ConcurrentHashMap}'s value type\n * @param k1 the mapping's key\n * @param v1 the mapping's value\n * @return a {@code ConcurrentHashMap} containing the specified mapping\n * @throws NullPointerException if the key or the value is {@code null}\n */\n public static ConcurrentHashMap of(K k1, V v1) {\n return new ConcurrentHashMap<>(ImmutableMap.of(k1, v1));\n }\n\n /**\n * Returns a new {@code ConcurrentHashMap} containing two mappings. This method leverages {@code\n * java.util.Map.of} for initial validation.\n *\n * @param the {@code ConcurrentHashMap}'s key type\n * @param the {@code ConcurrentHashMap}'s value type\n * @param k1 the first mapping's key\n * @param v1 the first mapping's value\n * @param k2 the second mapping's key\n * @param v2 the second mapping's value\n * @return a {@code ConcurrentHashMap} containing the specified mappings\n */\n public static ConcurrentHashMap of(K k1, V v1, K k2, V v2) {\n return new ConcurrentHashMap<>(ImmutableMap.of(k1, v1, k2, v2));\n }\n\n /**\n * Returns a new {@code ConcurrentHashMap} containing three mappings. This method leverages {@code\n * java.util.Map.of} for initial validation.\n *\n * @param the {@code ConcurrentHashMap}'s key type\n * @param the {@code ConcurrentHashMap}'s value type\n * @param k1 the first mapping's key\n * @param v1 the first mapping's value\n * @param k2 the second mapping's key\n * @param v2 the second mapping's value\n * @param k3 the third mapping's key\n * @param v3 the third mapping's value\n * @return a {@code ConcurrentHashMap} containing the specified mappings\n */\n public static ConcurrentHashMap of(K k1, V v1, K k2, V v2, K k3, V v3) {\n return new ConcurrentHashMap<>(ImmutableMap.of(k1, v1, k2, v2, k3, v3));\n }\n\n /**\n * Returns a new {@code ConcurrentHashMap} containing four mappings. This method leverages {@code\n * java.util.Map.of} for initial validation.\n *\n * @param the {@code ConcurrentHashMap}'s key type\n * @param the {@code ConcurrentHashMap}'s value type\n * @param k1 the first mapping's key\n * @param v1 the first mapping's value\n * @param k2 the second mapping's key\n * @param v2 the second mapping's value\n * @param k3 the third mapping's key\n * @param v3 the third mapping's value\n * @param k4 the fourth mapping's key\n * @param v4 the fourth mapping's value\n * @return a {@code ConcurrentHashMap} containing the specified mappings\n */\n public static ConcurrentHashMap of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {\n return new ConcurrentHashMap<>(ImmutableMap.of(k1, v1, k2, v2, k3, v3, k4, v4));\n }\n\n /**\n * Returns a new {@code ConcurrentHashMap} containing five mappings. This method leverages {@code\n * java.util.Map.of} for initial validation.\n *\n * @param the {@code ConcurrentHashMap}'s key type\n * @param the {@code ConcurrentHashMap}'s value type\n * @param k1 the first mapping's key\n * @param v1 the first mapping's value\n * @param k2 the second mapping's key\n * @param v2 the second mapping's value\n * @param k3 the third mapping's key\n * @param v3 the third mapping's value\n * @param k4 the fourth mapping's key\n * @param v4 the fourth mapping's value\n * @param k5 the fifth mapping's key\n * @param v5 the fifth mapping's value\n * @return a {@code ConcurrentHashMap} containing the specified mappings\n */\n public static ConcurrentHashMap of(\n K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {\n return new ConcurrentHashMap<>(ImmutableMap.of(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5));\n }\n\n /**\n * Returns a new {@code ConcurrentHashMap} containing six mappings. This method leverages {@code\n * java.util.Map.of} for initial validation.\n *\n * @param the {@code ConcurrentHashMap}'s key type\n * @param the {@code ConcurrentHashMap}'s value type\n * @param k1 the first mapping's key\n * @param v1 the first mapping's value\n * @param k2 the second mapping's key\n * @param v2 the second mapping's value\n * @param k3 the third mapping's key\n * @param v3 the third mapping's value\n * @param k4 the fourth mapping's key\n * @param v4 the fourth mapping's value\n * @param k5 the fifth mapping's key\n * @param v5 the fifth mapping's value\n * @param k6 the sixth mapping's key\n * @param v6 the sixth mapping's value\n * @return a {@code ConcurrentHashMap} containing the specified mappings\n * @throws IllegalArgumentException if there are any duplicate keys (behavior inherited from\n * Map.of)\n * @throws NullPointerException if any key or value is {@code null} (behavior inherited from\n * Map.of)\n */\n public static ConcurrentHashMap of(\n K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6) {\n return new ConcurrentHashMap<>(ImmutableMap.of(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6));\n }\n\n /**\n * Returns a new {@code ConcurrentHashMap} containing seven mappings. This method leverages {@code\n * java.util.Map.of} for initial validation.\n *\n * @param the {@code ConcurrentHashMap}'s key type\n * @param the {@code ConcurrentHashMap}'s value type\n * @param k1 the first mapping's key\n * @param v1 the first mapping's value\n * @param k2 the second mapping's key\n * @param v2 the second mapping's value\n * @param k3 the third mapping's key\n * @param v3 the third mapping's value\n * @param k4 the fourth mapping's key\n * @param v4 the fourth mapping's value\n * @param k5 the fifth mapping's key\n * @param v5 the fifth mapping's value\n * @param k6 the sixth mapping's key\n * @param v6 the sixth mapping's value\n * @param k7 the seventh mapping's key\n * @param v7 the seventh mapping's value\n * @return a {@code ConcurrentHashMap} containing the specified mappings\n */\n public static ConcurrentHashMap of(\n K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7) {\n return new ConcurrentHashMap<>(\n ImmutableMap.of(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6, k7, v7));\n }\n\n /**\n * Returns a new {@code ConcurrentHashMap} containing eight mappings. This method leverages {@code\n * java.util.Map.of} for initial validation.\n *\n * @param the {@code ConcurrentHashMap}'s key type\n * @param the {@code ConcurrentHashMap}'s value type\n * @param k1 the first mapping's key\n * @param v1 the first mapping's value\n * @param k2 the second mapping's key\n * @param v2 the second mapping's value\n * @param k3 the third mapping's key\n * @param v3 the third mapping's value\n * @param k4 the fourth mapping's key\n * @param v4 the fourth mapping's value\n * @param k5 the fifth mapping's key\n * @param v5 the fifth mapping's value\n * @param k6 the sixth mapping's key\n * @param v6 the sixth mapping's value\n * @param k7 the seventh mapping's key\n * @param v7 the seventh mapping's value\n * @param k8 the eighth mapping's key\n * @param v8 the eighth mapping's value\n * @return a {@code ConcurrentHashMap} containing the specified mappings\n */\n public static ConcurrentHashMap of(\n K k1,\n V v1,\n K k2,\n V v2,\n K k3,\n V v3,\n K k4,\n V v4,\n K k5,\n V v5,\n K k6,\n V v6,\n K k7,\n V v7,\n K k8,\n V v8) {\n return new ConcurrentHashMap<>(\n ImmutableMap.of(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6, k7, v7, k8, v8));\n }\n\n /**\n * Returns a new {@code ConcurrentHashMap} containing nine mappings. This method leverages {@code\n * java.util.Map.of} for initial validation.\n *\n * @param the {@code ConcurrentHashMap}'s key type\n * @param the {@code ConcurrentHashMap}'s value type\n * @param k1 the first mapping's key\n * @param v1 the first mapping's value\n * @param k2 the second mapping's key\n * @param v2 the second mapping's value\n * @param k3 the third mapping's key\n * @param v3 the third mapping's value\n * @param k4 the fourth mapping's key\n * @param v4 the fourth mapping's value\n * @param k5 the fifth mapping's key\n * @param v5 the fifth mapping's value\n * @param k6 the sixth mapping's key\n * @param v6 the sixth mapping's value\n * @param k7 the seventh mapping's key\n * @param v7 the seventh mapping's value\n * @param k8 the eighth mapping's key\n * @param v8 the eighth mapping's value\n * @param k9 the ninth mapping's key\n * @param v9 the ninth mapping's value\n * @return a {@code ConcurrentHashMap} containing the specified mappings\n */\n public static ConcurrentHashMap of(\n K k1,\n V v1,\n K k2,\n V v2,\n K k3,\n V v3,\n K k4,\n V v4,\n K k5,\n V v5,\n K k6,\n V v6,\n K k7,\n V v7,\n K k8,\n V v8,\n K k9,\n V v9) {\n return new ConcurrentHashMap<>(\n ImmutableMap.of(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6, k7, v7, k8, v8, k9, v9));\n }\n\n /**\n * Returns a new {@code ConcurrentHashMap} containing ten mappings. This method leverages {@code\n * java.util.Map.of} for initial validation.\n *\n * @param the {@code ConcurrentHashMap}'s key type\n * @param the {@code ConcurrentHashMap}'s value type\n * @param k1 the first mapping's key\n * @param v1 the first mapping's value\n * @param k2 the second mapping's key\n * @param v2 the second mapping's value\n * @param k3 the third mapping's key\n * @param v3 the third mapping's value\n * @param k4 the fourth mapping's key\n * @param v4 the fourth mapping's value\n * @param k5 the fifth mapping's key\n * @param v5 the fifth mapping's value\n * @param k6 the sixth mapping's key\n * @param v6 the sixth mapping's value\n * @param k7 the seventh mapping's key\n * @param v7 the seventh mapping's value\n * @param k8 the eighth mapping's key\n * @param v8 the eighth mapping's value\n * @param k9 the ninth mapping's key\n * @param v9 the ninth mapping's value\n * @param k10 the tenth mapping's key\n * @param v10 the tenth mapping's value\n * @return a {@code ConcurrentHashMap} containing the specified mappings\n */\n public static ConcurrentHashMap of(\n K k1,\n V v1,\n K k2,\n V v2,\n K k3,\n V v3,\n K k4,\n V v4,\n K k5,\n V v5,\n K k6,\n V v6,\n K k7,\n V v7,\n K k8,\n V v8,\n K k9,\n V v9,\n K k10,\n V v10) {\n return new ConcurrentHashMap<>(\n ImmutableMap.of(\n k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6, k7, v7, k8, v8, k9, v9, k10, v10));\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/artifacts/ListArtifactsResponse.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.artifacts;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\nimport java.util.List;\n\n/** Response for listing artifacts. */\n@AutoValue\npublic abstract class ListArtifactsResponse {\n\n public abstract ImmutableList filenames();\n\n /** Builder for {@link ListArtifactsResponse}. */\n @AutoValue.Builder\n public abstract static class Builder {\n public abstract Builder filenames(List filenames);\n\n public abstract ListArtifactsResponse build();\n }\n\n public static Builder builder() {\n return new AutoValue_ListArtifactsResponse.Builder();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/sessions/HttpApiResponse.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\nimport okhttp3.Response;\nimport okhttp3.ResponseBody;\n\n/** Wraps a real HTTP response to expose the methods needed by the GenAI SDK. */\npublic final class HttpApiResponse extends ApiResponse {\n\n private final Response response;\n\n /** Constructs a HttpApiResponse instance with the response. */\n public HttpApiResponse(Response response) {\n this.response = response;\n }\n\n /** Returns the HttpEntity from the response. */\n @Override\n public ResponseBody getResponseBody() {\n return response.body();\n }\n\n /** Closes the Http response. */\n @Override\n public void close() {\n response.close();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/llmflows/audio/VertexSpeechClient.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows.llmflows.audio;\n\nimport com.google.cloud.speech.v1.RecognitionAudio;\nimport com.google.cloud.speech.v1.RecognitionConfig;\nimport com.google.cloud.speech.v1.RecognizeResponse;\nimport com.google.cloud.speech.v1.SpeechClient;\nimport java.io.IOException;\n\n/** Implementation of SpeechClientInterface using Vertex AI SpeechClient. */\npublic class VertexSpeechClient implements SpeechClientInterface {\n\n private final SpeechClient speechClient;\n\n /**\n * Constructs a VertexSpeechClient, initializing the underlying Google Cloud SpeechClient.\n *\n * @throws IOException if SpeechClient creation fails.\n */\n public VertexSpeechClient() throws IOException {\n this.speechClient = SpeechClient.create();\n }\n\n /**\n * Performs synchronous speech recognition on the given audio input.\n *\n * @param config Recognition configuration (e.g., language, encoding).\n * @param audio Audio data to recognize.\n * @return The recognition result.\n */\n @Override\n public RecognizeResponse recognize(RecognitionConfig config, RecognitionAudio audio) {\n // The original SpeechClient.recognize doesn't declare checked exceptions other than what might\n // be runtime. The interface declares Exception to be more general for other implementations.\n return speechClient.recognize(config, audio);\n }\n\n @Override\n public void close() throws Exception {\n if (speechClient != null) {\n speechClient.close();\n }\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/agents/Instruction.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.agents;\n\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.function.Function;\n\n/**\n * Represents an instruction that can be provided to an agent to guide its behavior.\n *\n *

In the instructions, you should describe concisely what the agent will do, when it should\n * defer to other agents/tools, and how it should respond to the user.\n *\n *

Templating is supported using placeholders like {@code {variable_name}} or {@code\n * {artifact.artifact_name}}. These are replaced with values from the agent's session state or\n * loaded artifacts, respectively. For example, an instruction like {@code \"Translate the following\n * text to {language}: {user_query}\"} would substitute {@code {language}} and {@code {user_query}}\n * with their corresponding values from the session state.\n *\n *

Instructions can also be dynamically constructed using {@link Instruction.Provider}. This\n * allows for more complex logic where the instruction text is generated based on the current {@link\n * ReadonlyContext}. Additionally, an instruction could be built to include specific information\n * based on based on some external factors fetched during the Provider call like the current time,\n * the result of some API call, etc.\n */\npublic sealed interface Instruction permits Instruction.Static, Instruction.Provider {\n /** Plain instruction directly provided to the agent. */\n record Static(String instruction) implements Instruction {}\n\n /** Returns an instruction dynamically constructed from the given context. */\n record Provider(Function> getInstruction)\n implements Instruction {}\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/utils/CollectionUtils.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.utils;\n\nimport com.google.common.collect.Iterables;\n\n/** Frequently used code snippets for collections. */\npublic final class CollectionUtils {\n\n /**\n * Checks if the given iterable is null or empty.\n *\n * @param iterable the iterable to check\n * @return true if the iterable is null or empty, false otherwise\n */\n public static boolean isNullOrEmpty(Iterable iterable) {\n return iterable == null || Iterables.isEmpty(iterable);\n }\n\n private CollectionUtils() {}\n}\n"], ["/adk-java/dev/src/main/java/com/google/adk/web/config/AdkWebCorsConfig.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.web.config;\n\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.web.cors.CorsConfiguration;\nimport org.springframework.web.cors.CorsConfigurationSource;\nimport org.springframework.web.cors.UrlBasedCorsConfigurationSource;\nimport org.springframework.web.filter.CorsFilter;\n\n/**\n * Configuration class for setting up Cross-Origin Resource Sharing (CORS) in the ADK Web\n * application. This class defines beans for configuring CORS settings based on properties defined\n * in {@link AdkWebCorsProperties}.\n *\n *

CORS allows the application to handle requests from different origins, enabling secure\n * communication between the frontend and backend services.\n *\n *

Beans provided:\n *\n *

    \n *
  • {@link CorsConfigurationSource}: Configures CORS settings such as allowed origins, methods,\n * headers, credentials, and max age.\n *
  • {@link CorsFilter}: Applies the CORS configuration to incoming requests.\n *
\n */\n@Configuration\npublic class AdkWebCorsConfig {\n\n @Bean\n public CorsConfigurationSource corsConfigurationSource(AdkWebCorsProperties corsProperties) {\n CorsConfiguration configuration = new CorsConfiguration();\n\n configuration.setAllowedOrigins(corsProperties.origins());\n configuration.setAllowedMethods(corsProperties.methods());\n configuration.setAllowedHeaders(corsProperties.headers());\n configuration.setAllowCredentials(corsProperties.allowCredentials());\n configuration.setMaxAge(corsProperties.maxAge());\n\n UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();\n source.registerCorsConfiguration(corsProperties.mapping(), configuration);\n\n return source;\n }\n\n @Bean\n public CorsFilter corsFilter(CorsConfigurationSource corsConfigurationSource) {\n return new CorsFilter(corsConfigurationSource);\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/network/ApiResponse.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.network;\n\nimport okhttp3.ResponseBody;\n\n/** The API response contains a response to a call to the GenAI APIs. */\npublic abstract class ApiResponse implements AutoCloseable {\n /** Gets the ResponseBody. */\n public abstract ResponseBody getEntity();\n\n @Override\n public abstract void close();\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/sessions/ApiResponse.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\nimport okhttp3.ResponseBody;\n\n/** The API response contains a response to a call to the GenAI APIs. */\npublic abstract class ApiResponse implements AutoCloseable {\n /** Gets the HttpEntity. */\n public abstract ResponseBody getResponseBody();\n\n @Override\n public abstract void close();\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/llmflows/audio/SpeechClientInterface.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows.llmflows.audio;\n\nimport com.google.cloud.speech.v1.RecognitionAudio;\nimport com.google.cloud.speech.v1.RecognitionConfig;\nimport com.google.cloud.speech.v1.RecognizeResponse;\n\n/**\n * Interface for a speech-to-text client. Allows for different implementations (e.g., Cloud, Mocks).\n */\npublic interface SpeechClientInterface extends AutoCloseable {\n\n /**\n * Performs synchronous speech recognition.\n *\n * @param config The recognition configuration.\n * @param audio The audio data to transcribe.\n * @return The recognition response.\n * @throws Exception if an error occurs during recognition.\n */\n RecognizeResponse recognize(RecognitionConfig config, RecognitionAudio audio) throws Exception;\n\n /**\n * Closes the client and releases any resources.\n *\n * @throws Exception if an error occurs during closing.\n */\n @Override\n void close() throws Exception;\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/Version.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk;\n\n/**\n * Tracks the current ADK version. Useful for tracking headers. Kept as a string literal to avoid\n * coupling with the build system.\n */\npublic final class Version {\n // Don't touch this, release-please should keep it up to date.\n public static final String JAVA_ADK_VERSION = \"0.2.1-SNAPSHOT\";\n\n private Version() {}\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/mcp/McpTransportBuilder.java", "package com.google.adk.tools.mcp;\n\nimport io.modelcontextprotocol.spec.McpClientTransport;\n\n/**\n * Interface for building McpClientTransport instances. Implementations of this interface are\n * responsible for constructing concrete McpClientTransport objects based on the provided connection\n * parameters.\n */\npublic interface McpTransportBuilder {\n /**\n * Builds an McpClientTransport based on the provided connection parameters.\n *\n * @param connectionParams The parameters required to configure the transport. The type of this\n * object determines the type of transport built.\n * @return An instance of McpClientTransport.\n * @throws IllegalArgumentException if the connectionParams are not supported or invalid.\n */\n McpClientTransport build(Object connectionParams);\n}\n"]], "task_instance_info": {"created_time": "2025-08-20 20:39:51", "created_task_model": "DeepSeek-R1", "function_skeleton": "@Override\n public Optional declaration () {}", "code_description": "This code segment functions to: Define the interface specification for an external service call by constructing a structured parameter schema that requires a textual search input."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```java\n[TASK_BEGIN]\n@Override\npublic Optional declaration() {\n return Optional.of(\n FunctionDeclaration.newBuilder()\n .setName(getName())\n .setDescription(getDescription())\n .setParameters(Schema.newBuilder().build())\n .build());\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 20-40-02"}, "editdistance_info": {"edit_distance": 27.2727, "calculate_time": "2025-08-20 20:40:02", "true_code_clean": "@Override\n public Optional declaration() {\n Schema querySchema =\n Schema.builder().type(\"STRING\").description(\"The query to retrieve.\").build();\n Schema parametersSchema =\n Schema.builder()\n .type(\"OBJECT\")\n .properties(Collections.singletonMap(\"query\", querySchema))\n .build();\n return Optional.of(\n FunctionDeclaration.builder()\n .name(this.name())\n .description(this.description())\n .parameters(parametersSchema)\n .build());\n }", "predict_code_clean": "@Override\npublic Optional declaration() {\n return Optional.of(\n FunctionDeclaration.newBuilder()\n .setName(getName())\n .setDescription(getDescription())\n .setParameters(Schema.newBuilder().build())\n .build());\n}"}} {"repo_name": "adk-java", "file_name": "/adk-java/core/src/main/java/com/google/adk/models/Gemini.java", "inference_info": {"prefix_code": "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.models;\n\nimport static com.google.common.base.StandardSystemProperty.JAVA_VERSION;\nimport static com.google.common.collect.ImmutableList.toImmutableList;\n\nimport com.google.adk.Version;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport com.google.genai.Client;\nimport com.google.genai.ResponseStream;\nimport com.google.genai.types.Blob;\nimport com.google.genai.types.Candidate;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.FileData;\nimport com.google.genai.types.FinishReason;\nimport com.google.genai.types.GenerateContentConfig;\nimport com.google.genai.types.GenerateContentResponse;\nimport com.google.genai.types.HttpOptions;\nimport com.google.genai.types.LiveConnectConfig;\nimport com.google.genai.types.Part;\nimport io.reactivex.rxjava3.core.Flowable;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Objects;\nimport java.util.Optional;\nimport java.util.concurrent.CompletableFuture;\nimport java.util.stream.Stream;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * Represents the Gemini Generative AI model.\n *\n *

This class provides methods for interacting with the Gemini model, including standard\n * request-response generation and establishing persistent bidirectional connections.\n */\npublic class Gemini extends BaseLlm {\n\n private static final Logger logger = LoggerFactory.getLogger(Gemini.class);\n private static final ImmutableMap TRACKING_HEADERS;\n\n static {\n String frameworkLabel = \"google-adk/\" + Version.JAVA_ADK_VERSION;\n String languageLabel = \"gl-java/\" + JAVA_VERSION.value();\n String versionHeaderValue = String.format(\"%s %s\", frameworkLabel, languageLabel);\n\n TRACKING_HEADERS =\n ImmutableMap.of(\n \"x-goog-api-client\", versionHeaderValue,\n \"user-agent\", versionHeaderValue);\n }\n\n private final Client apiClient;\n\n private static final String CONTINUE_OUTPUT_MESSAGE =\n \"Continue output. DO NOT look at this line. ONLY look at the content before this line and\"\n + \" system instruction.\";\n\n /**\n * Constructs a new Gemini instance.\n *\n * @param modelName The name of the Gemini model to use (e.g., \"gemini-2.0-flash\").\n * @param apiClient The genai {@link com.google.genai.Client} instance for making API calls.\n */\n public Gemini(String modelName, Client apiClient) {\n super(modelName);\n this.apiClient = Objects.requireNonNull(apiClient, \"apiClient cannot be null\");\n }\n\n /**\n * Constructs a new Gemini instance with a Google Gemini API key.\n *\n * @param modelName The name of the Gemini model to use (e.g., \"gemini-2.0-flash\").\n * @param apiKey The Google Gemini API key.\n */\n public Gemini(String modelName, String apiKey) {\n super(modelName);\n Objects.requireNonNull(apiKey, \"apiKey cannot be null\");\n this.apiClient =\n Client.builder()\n .apiKey(apiKey)\n .httpOptions(HttpOptions.builder().headers(TRACKING_HEADERS).build())\n .build();\n }\n\n /**\n * Constructs a new Gemini instance with a Google Gemini API key.\n *\n * @param modelName The name of the Gemini model to use (e.g., \"gemini-2.0-flash\").\n * @param vertexCredentials The Vertex AI credentials to access the Gemini model.\n */\n public Gemini(String modelName, VertexCredentials vertexCredentials) {\n super(modelName);\n Objects.requireNonNull(vertexCredentials, \"vertexCredentials cannot be null\");\n Client.Builder apiClientBuilder =\n Client.builder().httpOptions(HttpOptions.builder().headers(TRACKING_HEADERS).build());\n vertexCredentials.project().ifPresent(apiClientBuilder::project);\n vertexCredentials.location().ifPresent(apiClientBuilder::location);\n vertexCredentials.credentials().ifPresent(apiClientBuilder::credentials);\n this.apiClient = apiClientBuilder.build();\n }\n\n /**\n * Returns a new Builder instance for constructing Gemini objects. Note that when building a\n * Gemini object, at least one of apiKey, vertexCredentials, or an explicit apiClient must be set.\n * If multiple are set, the explicit apiClient will take precedence.\n *\n * @return A new {@link Builder}.\n */\n public static Builder builder() {\n return new Builder();\n }\n\n /** Builder for {@link Gemini}. */\n public static class Builder {\n private String modelName;\n private Client apiClient;\n private String apiKey;\n private VertexCredentials vertexCredentials;\n\n private Builder() {}\n\n /**\n * Sets the name of the Gemini model to use.\n *\n * @param modelName The model name (e.g., \"gemini-2.0-flash\").\n * @return This builder.\n */\n @CanIgnoreReturnValue\n public Builder modelName(String modelName) {\n this.modelName = modelName;\n return this;\n }\n\n /**\n * Sets the explicit {@link com.google.genai.Client} instance for making API calls. If this is\n * set, apiKey and vertexCredentials will be ignored.\n *\n * @param apiClient The client instance.\n * @return This builder.\n */\n @CanIgnoreReturnValue\n public Builder apiClient(Client apiClient) {\n this.apiClient = apiClient;\n return this;\n }\n\n /**\n * Sets the Google Gemini API key. If {@link #apiClient(Client)} is also set, the explicit\n * client will take precedence. If {@link #vertexCredentials(VertexCredentials)} is also set,\n * this apiKey will take precedence.\n *\n * @param apiKey The API key.\n * @return This builder.\n */\n @CanIgnoreReturnValue\n public Builder apiKey(String apiKey) {\n this.apiKey = apiKey;\n return this;\n }\n\n /**\n * Sets the Vertex AI credentials. If {@link #apiClient(Client)} or {@link #apiKey(String)} are\n * also set, they will take precedence over these credentials.\n *\n * @param vertexCredentials The Vertex AI credentials.\n * @return This builder.\n */\n @CanIgnoreReturnValue\n public Builder vertexCredentials(VertexCredentials vertexCredentials) {\n this.vertexCredentials = vertexCredentials;\n return this;\n }\n\n /**\n * Builds the {@link Gemini} instance.\n *\n * @return A new {@link Gemini} instance.\n * @throws NullPointerException if modelName is null.\n */\n public Gemini build() {\n Objects.requireNonNull(modelName, \"modelName must be set.\");\n\n if (apiClient != null) {\n return new Gemini(modelName, apiClient);\n } else if (apiKey != null) {\n return new Gemini(modelName, apiKey);\n } else if (vertexCredentials != null) {\n return new Gemini(modelName, vertexCredentials);\n } else {\n return new Gemini(\n modelName,\n Client.builder()\n .httpOptions(HttpOptions.builder().headers(TRACKING_HEADERS).build())\n .build());\n }\n }\n }\n\n /**\n * Sanitizes the request to ensure it is compatible with the configured API backend. Required as\n * there are some parameters that if included in the request will raise a runtime error if sent to\n * the wrong backend (e.g. image names when the backend isn't Vertex AI).\n *\n * @param llmRequest The request to sanitize.\n * @return The sanitized request.\n */\n private LlmRequest sanitizeRequest(LlmRequest llmRequest) {\n if (apiClient.vertexAI()) {\n return llmRequest;\n }\n LlmRequest.Builder requestBuilder = llmRequest.toBuilder();\n\n // Using API key from Google AI Studio to call model doesn't support labels.\n llmRequest\n .config()\n .ifPresent(\n config -> {\n if (config.labels().isPresent()) {\n requestBuilder.config(config.toBuilder().labels(null).build());\n }\n });\n\n if (llmRequest.contents().isEmpty()) {\n return requestBuilder.build();\n }\n\n // This backend does not support the display_name parameter for file uploads,\n // so it must be removed to prevent request failures.\n ImmutableList updatedContents =\n llmRequest.contents().stream()\n .map(\n content -> {\n if (content.parts().isEmpty() || content.parts().get().isEmpty()) {\n return content;\n }\n\n ImmutableList updatedParts =\n content.parts().get().stream()\n .map(\n part -> {\n Part.Builder partBuilder = part.toBuilder();\n if (part.inlineData().flatMap(Blob::displayName).isPresent()) {\n Blob blob = part.inlineData().get();\n Blob.Builder newBlobBuilder = Blob.builder();\n blob.data().ifPresent(newBlobBuilder::data);\n blob.mimeType().ifPresent(newBlobBuilder::mimeType);\n partBuilder.inlineData(newBlobBuilder.build());\n }\n if (part.fileData().flatMap(FileData::displayName).isPresent()) {\n FileData fileData = part.fileData().get();\n FileData.Builder newFileDataBuilder = FileData.builder();\n fileData.fileUri().ifPresent(newFileDataBuilder::fileUri);\n fileData.mimeType().ifPresent(newFileDataBuilder::mimeType);\n partBuilder.fileData(newFileDataBuilder.build());\n }\n return partBuilder.build();\n })\n .collect(toImmutableList());\n\n return content.toBuilder().parts(updatedParts).build();\n })\n .collect(toImmutableList());\n return requestBuilder.contents(updatedContents).build();\n }\n\n @Override\n public Flowable generateContent(LlmRequest llmRequest, boolean stream) {\n llmRequest = sanitizeRequest(llmRequest);\n List contents = llmRequest.contents();\n // Last content must be from the user, otherwise the model won't respond.\n if (contents.isEmpty() || !Iterables.getLast(contents).role().orElse(\"\").equals(\"user\")) {\n Content userContent = Content.fromParts(Part.fromText(CONTINUE_OUTPUT_MESSAGE));\n contents =\n Stream.concat(contents.stream(), Stream.of(userContent)).collect(toImmutableList());\n }\n\n List finalContents = stripThoughts(contents);\n GenerateContentConfig config = llmRequest.config().orElse(null);\n String effectiveModelName = llmRequest.model().orElse(model());\n\n logger.trace(\"Request Contents: {}\", finalContents);\n logger.trace(\"Request Config: {}\", config);\n\n if (stream) {\n logger.debug(\"Sending streaming generateContent request to model {}\", effectiveModelName);\n CompletableFuture> streamFuture =\n apiClient.async.models.generateContentStream(effectiveModelName, finalContents, config);\n\n return Flowable.defer(\n () -> {\n final StringBuilder accumulatedText = new StringBuilder();\n // Array to bypass final local variable reassignment in lambda.\n final GenerateContentResponse[] lastRawResponseHolder = {null};\n\n return Flowable.fromFuture(streamFuture)\n .flatMapIterable(iterable -> iterable)\n .concatMap(\n rawResponse -> {\n lastRawResponseHolder[0] = rawResponse;\n logger.trace(\"Raw streaming response: {}\", rawResponse);\n\n List responsesToEmit = new ArrayList<>();\n LlmResponse currentProcessedLlmResponse = LlmResponse.create(rawResponse);\n String currentTextChunk = getTextFromLlmResponse(currentProcessedLlmResponse);\n\n if (!currentTextChunk.isEmpty()) {\n accumulatedText.append(currentTextChunk);\n LlmResponse partialResponse =\n currentProcessedLlmResponse.toBuilder().partial(true).build();\n responsesToEmit.add(partialResponse);\n } else {\n if (accumulatedText.length() > 0\n && shouldEmitAccumulatedText(currentProcessedLlmResponse)) {\n LlmResponse aggregatedTextResponse =\n LlmResponse.builder()\n .content(\n Content.builder()\n .parts(\n ImmutableList.of(\n Part.builder()\n .text(accumulatedText.toString())\n .build()))\n .build())\n .build();\n responsesToEmit.add(aggregatedTextResponse);\n accumulatedText.setLength(0);\n }\n responsesToEmit.add(currentProcessedLlmResponse);\n }\n logger.debug(\"Responses to emit: {}\", responsesToEmit);\n return Flowable.fromIterable(responsesToEmit);\n })\n .concatWith(\n Flowable.defer(\n () -> {\n if (accumulatedText.length() > 0 && lastRawResponseHolder[0] != null) {\n GenerateContentResponse finalRawResp = lastRawResponseHolder[0];\n boolean isStop =\n finalRawResp\n .candidates()\n .flatMap(\n candidates ->\n candidates.isEmpty()\n ? Optional.empty()\n : Optional.of(candidates.get(0)))\n .flatMap(Candidate::finishReason)\n .map(\n finishReason ->\n finishReason.equals(\n new FinishReason(FinishReason.Known.STOP)))\n .orElse(false);\n\n if (isStop) {\n LlmResponse finalAggregatedTextResponse =\n LlmResponse.builder()\n .content(\n Content.builder()\n .parts(\n ImmutableList.of(\n Part.builder()\n .text(accumulatedText.toString())\n .build()))\n .build())\n .build();\n return Flowable.just(finalAggregatedTextResponse);\n }\n }\n return Flowable.empty();\n }));\n });\n } else {\n logger.debug(\"Sending generateContent request to model {}\", effectiveModelName);\n return Flowable.fromFuture(\n apiClient\n .async\n .models\n .generateContent(effectiveModelName, finalContents, config)\n .thenApplyAsync(LlmResponse::create));\n }\n }\n\n /**\n * Extracts text content from the first part of an LlmResponse, if available.\n *\n * @param llmResponse The LlmResponse to extract text from.\n * @return The text content, or an empty string if not found.\n */\n private String getTextFromLlmResponse(LlmResponse llmResponse) {\n return llmResponse\n .content()\n .flatMap(Content::parts)\n .filter(parts -> !parts.isEmpty())\n .map(parts -> parts.get(0))\n .flatMap(Part::text)\n .orElse(\"\");\n }\n\n /**\n * Determines if accumulated text should be emitted based on the current LlmResponse. We flush if\n * current response is not a text continuation (e.g., no content, no parts, or the first part is\n * not inline_data, meaning it's something else or just empty, thereby warranting a flush of\n * preceding text).\n *\n * @param currentLlmResponse The current LlmResponse being processed.\n * @return True if accumulated text should be emitted, false otherwise.\n */\n private boolean shouldEmitAccumulatedText(LlmResponse currentLlmResponse) {\n Optional contentOpt = currentLlmResponse.content();\n if (contentOpt.isEmpty()) {\n return true;\n }\n\n Optional> partsOpt = contentOpt.get().parts();\n if (partsOpt.isEmpty() || partsOpt.get().isEmpty()) {\n return true;\n }\n\n // If content and parts are present, and parts list is not empty, we want to yield accumulated\n // text only if `text` is present AND (`not llm_response.content` OR `not\n // llm_response.content.parts` OR `not llm_response.content.parts[0].inline_data`)\n // This means we flush if the first part does NOT have inline_data.\n // If it *has* inline_data, the condition below is false,\n // and we would not flush based on this specific sub-condition.\n Part firstPart = partsOpt.get().get(0);\n return firstPart.inlineData().isEmpty();\n }\n\n @Override\n public BaseLlmConnection connect(LlmRequest llmRequest) {\n llmRequest = sanitizeRequest(llmRequest);\n logger.debug(\"Establishing Gemini connection.\");\n LiveConnectConfig liveConnectConfig = llmRequest.liveConnectConfig();\n String effectiveModelName = llmRequest.model().orElse(model());\n\n logger.debug(\"Connecting to model {}\", effectiveModelName);\n logger.trace(\"Connection Config: {}\", liveConnectConfig);\n\n return new GeminiLlmConnection(apiClient, effectiveModelName, liveConnectConfig);\n }\n\n /** Removes any `Part` that contains only a `thought` from the content list. */\n ", "suffix_code": "\n}\n", "middle_code": "private List stripThoughts(List originalContents) {\n List updatedContents = new ArrayList<>();\n for (Content content : originalContents) {\n ImmutableList nonThoughtParts =\n content.parts().orElse(ImmutableList.of()).stream()\n .filter(part -> part.thought().map(isThought -> !isThought).orElse(true))\n .collect(toImmutableList());\n updatedContents.add(content.toBuilder().parts(nonThoughtParts).build());\n }\n return updatedContents;\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "java", "sub_task_type": null}, "context_code": [["/adk-java/core/src/main/java/com/google/adk/models/GeminiLlmConnection.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.models;\n\nimport static com.google.common.collect.ImmutableList.toImmutableList;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.genai.AsyncSession;\nimport com.google.genai.Client;\nimport com.google.genai.types.Blob;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.FinishReason;\nimport com.google.genai.types.FunctionCall;\nimport com.google.genai.types.FunctionResponse;\nimport com.google.genai.types.LiveConnectConfig;\nimport com.google.genai.types.LiveSendClientContentParameters;\nimport com.google.genai.types.LiveSendRealtimeInputParameters;\nimport com.google.genai.types.LiveSendToolResponseParameters;\nimport com.google.genai.types.LiveServerContent;\nimport com.google.genai.types.LiveServerMessage;\nimport com.google.genai.types.LiveServerToolCall;\nimport com.google.genai.types.Part;\nimport io.reactivex.rxjava3.core.Completable;\nimport io.reactivex.rxjava3.core.Flowable;\nimport io.reactivex.rxjava3.processors.PublishProcessor;\nimport java.net.SocketException;\nimport java.util.List;\nimport java.util.Objects;\nimport java.util.Optional;\nimport java.util.concurrent.CompletableFuture;\nimport java.util.concurrent.CompletionException;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * Manages a persistent, bidirectional connection to the Gemini model via WebSockets for real-time\n * interaction.\n *\n *

This connection allows sending conversation history, individual messages, function responses,\n * and real-time media blobs (like audio chunks) while continuously receiving responses from the\n * model.\n */\npublic final class GeminiLlmConnection implements BaseLlmConnection {\n\n private static final Logger logger = LoggerFactory.getLogger(GeminiLlmConnection.class);\n\n private final Client apiClient;\n private final String modelName;\n private final LiveConnectConfig connectConfig;\n private final CompletableFuture sessionFuture;\n private final PublishProcessor responseProcessor = PublishProcessor.create();\n private final Flowable responseFlowable = responseProcessor.serialize();\n private final AtomicBoolean closed = new AtomicBoolean(false);\n\n /**\n * Establishes a new connection.\n *\n * @param apiClient The API client for communication.\n * @param modelName The specific Gemini model endpoint (e.g., \"gemini-2.0-flash).\n * @param connectConfig Configuration parameters for the live session.\n */\n GeminiLlmConnection(Client apiClient, String modelName, LiveConnectConfig connectConfig) {\n this.apiClient = Objects.requireNonNull(apiClient);\n this.modelName = Objects.requireNonNull(modelName);\n this.connectConfig = Objects.requireNonNull(connectConfig);\n\n this.sessionFuture =\n this.apiClient\n .async\n .live\n .connect(this.modelName, this.connectConfig)\n .whenCompleteAsync(\n (session, throwable) -> {\n if (throwable != null) {\n handleConnectionError(throwable);\n } else if (session != null) {\n setupReceiver(session);\n } else if (!closed.get()) {\n handleConnectionError(\n new SocketException(\"WebSocket connection failed without explicit error.\"));\n }\n });\n }\n\n /** Configures the session to forward incoming messages to the response processor. */\n private void setupReceiver(AsyncSession session) {\n if (closed.get()) {\n closeSessionIgnoringErrors(session);\n return;\n }\n session\n .receive(this::handleServerMessage)\n .exceptionally(\n error -> {\n handleReceiveError(error);\n return null;\n });\n }\n\n /** Processes messages received from the WebSocket server. */\n private void handleServerMessage(LiveServerMessage message) {\n if (closed.get()) {\n return;\n }\n\n logger.debug(\"Received server message: {}\", message.toJson());\n\n Optional llmResponse = convertToServerResponse(message);\n llmResponse.ifPresent(responseProcessor::onNext);\n }\n\n /** Converts a server message into the standardized LlmResponse format. */\n private Optional convertToServerResponse(LiveServerMessage message) {\n LlmResponse.Builder builder = LlmResponse.builder();\n\n if (message.serverContent().isPresent()) {\n LiveServerContent serverContent = message.serverContent().get();\n serverContent.modelTurn().ifPresent(builder::content);\n builder\n .partial(serverContent.turnComplete().map(completed -> !completed).orElse(false))\n .turnComplete(serverContent.turnComplete().orElse(false));\n } else if (message.toolCall().isPresent()) {\n LiveServerToolCall toolCall = message.toolCall().get();\n toolCall\n .functionCalls()\n .ifPresent(\n calls -> {\n for (FunctionCall call : calls) {\n builder.content(\n Content.builder()\n .parts(ImmutableList.of(Part.builder().functionCall(call).build()))\n .build());\n }\n });\n builder.partial(false).turnComplete(false);\n } else if (message.usageMetadata().isPresent()) {\n logger.debug(\"Received usage metadata: {}\", message.usageMetadata().get());\n return Optional.empty();\n } else if (message.toolCallCancellation().isPresent()) {\n logger.debug(\"Received tool call cancellation: {}\", message.toolCallCancellation().get());\n // TODO: implement proper CFC and thus tool call cancellation handling.\n return Optional.empty();\n } else if (message.setupComplete().isPresent()) {\n logger.debug(\"Received setup complete.\");\n return Optional.empty();\n } else {\n logger.warn(\"Received unknown or empty server message: {}\", message.toJson());\n builder\n .errorCode(new FinishReason(\"Unknown server message.\"))\n .errorMessage(\"Received unknown server message.\");\n }\n\n return Optional.of(builder.build());\n }\n\n /** Handles errors that occur *during* the initial connection attempt. */\n private void handleConnectionError(Throwable throwable) {\n if (closed.compareAndSet(false, true)) {\n logger.error(\"WebSocket connection failed\", throwable);\n Throwable cause =\n (throwable instanceof CompletionException) ? throwable.getCause() : throwable;\n responseProcessor.onError(cause);\n }\n }\n\n /** Handles errors reported by the WebSocket client *after* connection (e.g., receive errors). */\n private void handleReceiveError(Throwable throwable) {\n if (closed.compareAndSet(false, true)) {\n logger.error(\"Error during WebSocket receive operation\", throwable);\n responseProcessor.onError(throwable);\n sessionFuture.thenAccept(this::closeSessionIgnoringErrors).exceptionally(err -> null);\n }\n }\n\n @Override\n public Completable sendHistory(List history) {\n return sendClientContentInternal(\n LiveSendClientContentParameters.builder().turns(history).build());\n }\n\n @Override\n public Completable sendContent(Content content) {\n Objects.requireNonNull(content, \"content cannot be null\");\n\n Optional> functionResponses = extractFunctionResponses(content);\n\n if (functionResponses.isPresent()) {\n return sendToolResponseInternal(\n LiveSendToolResponseParameters.builder()\n .functionResponses(functionResponses.get())\n .build());\n } else {\n return sendClientContentInternal(\n LiveSendClientContentParameters.builder().turns(ImmutableList.of(content)).build());\n }\n }\n\n /** Extracts FunctionResponse parts from a Content object if all parts are FunctionResponses. */\n private Optional> extractFunctionResponses(Content content) {\n if (content.parts().isEmpty() || content.parts().get().isEmpty()) {\n return Optional.empty();\n }\n\n ImmutableList responses =\n content.parts().get().stream()\n .map(Part::functionResponse)\n .flatMap(Optional::stream)\n .collect(toImmutableList());\n\n // Ensure *all* parts were function responses\n if (responses.size() == content.parts().get().size()) {\n return Optional.of(responses);\n } else {\n return Optional.empty();\n }\n }\n\n @Override\n public Completable sendRealtime(Blob blob) {\n return Completable.fromFuture(\n sessionFuture.thenCompose(\n session ->\n session.sendRealtimeInput(\n LiveSendRealtimeInputParameters.builder().media(blob).build())));\n }\n\n /** Helper to send client content parameters. */\n private Completable sendClientContentInternal(LiveSendClientContentParameters parameters) {\n return Completable.fromFuture(\n sessionFuture.thenCompose(session -> session.sendClientContent(parameters)));\n }\n\n /** Helper to send tool response parameters. */\n private Completable sendToolResponseInternal(LiveSendToolResponseParameters parameters) {\n return Completable.fromFuture(\n sessionFuture.thenCompose(session -> session.sendToolResponse(parameters)));\n }\n\n @Override\n public Flowable receive() {\n return responseFlowable;\n }\n\n @Override\n public void close() {\n closeInternal(null);\n }\n\n @Override\n public void close(Throwable throwable) {\n Objects.requireNonNull(throwable, \"throwable cannot be null for close\");\n closeInternal(throwable);\n }\n\n /** Internal method to handle closing logic and signal completion/error. */\n private void closeInternal(Throwable throwable) {\n if (closed.compareAndSet(false, true)) {\n logger.debug(\"Closing GeminiConnection.\", throwable);\n\n if (throwable == null) {\n responseProcessor.onComplete();\n } else {\n responseProcessor.onError(throwable);\n }\n\n if (sessionFuture.isDone()) {\n sessionFuture.thenAccept(this::closeSessionIgnoringErrors).exceptionally(err -> null);\n } else {\n sessionFuture.cancel(false);\n }\n }\n }\n\n /** Closes the AsyncSession safely, logging any errors. */\n private void closeSessionIgnoringErrors(AsyncSession session) {\n if (session != null) {\n session\n .close()\n .exceptionally(\n closeError -> {\n logger.warn(\"Error occurred while closing AsyncSession\", closeError);\n return null; // Suppress error during close\n });\n }\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/llmflows/BaseLlmFlow.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows.llmflows;\n\nimport com.google.adk.Telemetry;\nimport com.google.adk.agents.BaseAgent;\nimport com.google.adk.agents.CallbackContext;\nimport com.google.adk.agents.Callbacks.AfterModelCallback;\nimport com.google.adk.agents.Callbacks.BeforeModelCallback;\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.agents.LiveRequest;\nimport com.google.adk.agents.LlmAgent;\nimport com.google.adk.agents.ReadonlyContext;\nimport com.google.adk.agents.RunConfig.StreamingMode;\nimport com.google.adk.events.Event;\nimport com.google.adk.exceptions.LlmCallsLimitExceededException;\nimport com.google.adk.flows.BaseFlow;\nimport com.google.adk.flows.llmflows.RequestProcessor.RequestProcessingResult;\nimport com.google.adk.flows.llmflows.ResponseProcessor.ResponseProcessingResult;\nimport com.google.adk.models.BaseLlm;\nimport com.google.adk.models.BaseLlmConnection;\nimport com.google.adk.models.LlmRegistry;\nimport com.google.adk.models.LlmRequest;\nimport com.google.adk.models.LlmResponse;\nimport com.google.adk.tools.ToolContext;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Iterables;\nimport com.google.genai.types.FunctionResponse;\nimport io.opentelemetry.api.trace.Span;\nimport io.opentelemetry.api.trace.StatusCode;\nimport io.opentelemetry.context.Scope;\nimport io.reactivex.rxjava3.core.Completable;\nimport io.reactivex.rxjava3.core.Flowable;\nimport io.reactivex.rxjava3.core.Maybe;\nimport io.reactivex.rxjava3.core.Single;\nimport io.reactivex.rxjava3.disposables.Disposable;\nimport io.reactivex.rxjava3.observers.DisposableCompletableObserver;\nimport io.reactivex.rxjava3.schedulers.Schedulers;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.Set;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/** A basic flow that calls the LLM in a loop until a final response is generated. */\npublic abstract class BaseLlmFlow implements BaseFlow {\n private static final Logger logger = LoggerFactory.getLogger(BaseLlmFlow.class);\n\n protected final List requestProcessors;\n protected final List responseProcessors;\n\n // Warning: This is local, in-process state that won't be preserved if the runtime is restarted.\n // \"Max steps\" is experimental and may evolve in the future (e.g., to support persistence).\n protected int stepsCompleted = 0;\n protected final int maxSteps;\n\n public BaseLlmFlow(\n List requestProcessors, List responseProcessors) {\n this(requestProcessors, responseProcessors, /* maxSteps= */ Optional.empty());\n }\n\n public BaseLlmFlow(\n List requestProcessors,\n List responseProcessors,\n Optional maxSteps) {\n this.requestProcessors = requestProcessors;\n this.responseProcessors = responseProcessors;\n this.maxSteps = maxSteps.orElse(Integer.MAX_VALUE);\n }\n\n /**\n * Pre-processes the LLM request before sending it to the LLM. Executes all registered {@link\n * RequestProcessor}.\n */\n protected Single preprocess(\n InvocationContext context, LlmRequest llmRequest) {\n\n List> eventIterables = new ArrayList<>();\n LlmAgent agent = (LlmAgent) context.agent();\n\n Single currentLlmRequest = Single.just(llmRequest);\n for (RequestProcessor processor : requestProcessors) {\n currentLlmRequest =\n currentLlmRequest\n .flatMap(request -> processor.processRequest(context, request))\n .doOnSuccess(\n result -> {\n if (result.events() != null) {\n eventIterables.add(result.events());\n }\n })\n .map(RequestProcessingResult::updatedRequest);\n }\n\n return currentLlmRequest.flatMap(\n processedRequest -> {\n LlmRequest.Builder updatedRequestBuilder = processedRequest.toBuilder();\n\n return agent\n .canonicalTools(new ReadonlyContext(context))\n .concatMapCompletable(\n tool ->\n tool.processLlmRequest(\n updatedRequestBuilder, ToolContext.builder(context).build()))\n .andThen(\n Single.fromCallable(\n () -> {\n Iterable combinedEvents = Iterables.concat(eventIterables);\n return RequestProcessingResult.create(\n updatedRequestBuilder.build(), combinedEvents);\n }));\n });\n }\n\n /**\n * Post-processes the LLM response after receiving it from the LLM. Executes all registered {@link\n * ResponseProcessor} instances. Handles function calls if present in the response.\n */\n protected Single postprocess(\n InvocationContext context,\n Event baseEventForLlmResponse,\n LlmRequest llmRequest,\n LlmResponse llmResponse) {\n\n List> eventIterables = new ArrayList<>();\n Single currentLlmResponse = Single.just(llmResponse);\n for (ResponseProcessor processor : responseProcessors) {\n currentLlmResponse =\n currentLlmResponse\n .flatMap(response -> processor.processResponse(context, response))\n .doOnSuccess(\n result -> {\n if (result.events() != null) {\n eventIterables.add(result.events());\n }\n })\n .map(ResponseProcessingResult::updatedResponse);\n }\n\n return currentLlmResponse.flatMap(\n updatedResponse -> {\n if (updatedResponse.content().isEmpty()\n && updatedResponse.errorCode().isEmpty()\n && !updatedResponse.interrupted().orElse(false)\n && !updatedResponse.turnComplete().orElse(false)) {\n return Single.just(\n ResponseProcessingResult.create(\n updatedResponse, Iterables.concat(eventIterables), Optional.empty()));\n }\n\n Event modelResponseEvent =\n buildModelResponseEvent(baseEventForLlmResponse, llmRequest, updatedResponse);\n eventIterables.add(Collections.singleton(modelResponseEvent));\n\n Maybe maybeFunctionCallEvent =\n modelResponseEvent.functionCalls().isEmpty()\n ? Maybe.empty()\n : Functions.handleFunctionCalls(context, modelResponseEvent, llmRequest.tools());\n\n return maybeFunctionCallEvent\n .map(Optional::of)\n .defaultIfEmpty(Optional.empty())\n .map(\n functionCallEventOpt -> {\n Optional transferToAgent = Optional.empty();\n if (functionCallEventOpt.isPresent()) {\n Event functionCallEvent = functionCallEventOpt.get();\n eventIterables.add(Collections.singleton(functionCallEvent));\n transferToAgent = functionCallEvent.actions().transferToAgent();\n }\n Iterable combinedEvents = Iterables.concat(eventIterables);\n return ResponseProcessingResult.create(\n updatedResponse, combinedEvents, transferToAgent);\n });\n });\n }\n\n /**\n * Sends a request to the LLM and returns its response.\n *\n * @param context The invocation context.\n * @param llmRequest The LLM request.\n * @param eventForCallbackUsage An Event object primarily for providing context (like actions) to\n * callbacks. Callbacks should not rely on its ID if they create their own separate events.\n */\n private Flowable callLlm(\n InvocationContext context, LlmRequest llmRequest, Event eventForCallbackUsage) {\n LlmAgent agent = (LlmAgent) context.agent();\n\n return handleBeforeModelCallback(context, llmRequest, eventForCallbackUsage)\n .flatMapPublisher(\n beforeResponse -> {\n if (beforeResponse.isPresent()) {\n return Flowable.just(beforeResponse.get());\n }\n BaseLlm llm =\n agent.resolvedModel().model().isPresent()\n ? agent.resolvedModel().model().get()\n : LlmRegistry.getLlm(agent.resolvedModel().modelName().get());\n return Flowable.defer(\n () -> {\n Span llmCallSpan =\n Telemetry.getTracer().spanBuilder(\"call_llm\").startSpan();\n\n try (Scope scope = llmCallSpan.makeCurrent()) {\n return llm.generateContent(\n llmRequest,\n context.runConfig().streamingMode() == StreamingMode.SSE)\n .doOnNext(\n llmResp -> {\n try (Scope innerScope = llmCallSpan.makeCurrent()) {\n Telemetry.traceCallLlm(\n context, eventForCallbackUsage.id(), llmRequest, llmResp);\n }\n })\n .doOnError(\n error -> {\n llmCallSpan.setStatus(StatusCode.ERROR, error.getMessage());\n llmCallSpan.recordException(error);\n })\n .doFinally(llmCallSpan::end);\n }\n })\n .concatMap(\n llmResp ->\n handleAfterModelCallback(context, llmResp, eventForCallbackUsage)\n .toFlowable());\n });\n }\n\n /**\n * Invokes {@link BeforeModelCallback}s. If any returns a response, it's used instead of calling\n * the LLM.\n *\n * @return A {@link Single} with the callback result or {@link Optional#empty()}.\n */\n private Single> handleBeforeModelCallback(\n InvocationContext context, LlmRequest llmRequest, Event modelResponseEvent) {\n LlmAgent agent = (LlmAgent) context.agent();\n\n Optional> callbacksOpt = agent.beforeModelCallback();\n if (callbacksOpt.isEmpty() || callbacksOpt.get().isEmpty()) {\n return Single.just(Optional.empty());\n }\n\n Event callbackEvent = modelResponseEvent.toBuilder().build();\n List callbacks = callbacksOpt.get();\n\n return Flowable.fromIterable(callbacks)\n .concatMapSingle(\n callback -> {\n CallbackContext callbackContext =\n new CallbackContext(context, callbackEvent.actions());\n return callback\n .call(callbackContext, llmRequest)\n .map(Optional::of)\n .defaultIfEmpty(Optional.empty());\n })\n .filter(Optional::isPresent)\n .firstElement()\n .switchIfEmpty(Single.just(Optional.empty()));\n }\n\n /**\n * Invokes {@link AfterModelCallback}s after an LLM response. If any returns a response, it\n * replaces the original.\n *\n * @return A {@link Single} with the final {@link LlmResponse}.\n */\n private Single handleAfterModelCallback(\n InvocationContext context, LlmResponse llmResponse, Event modelResponseEvent) {\n LlmAgent agent = (LlmAgent) context.agent();\n Optional> callbacksOpt = agent.afterModelCallback();\n\n if (callbacksOpt.isEmpty() || callbacksOpt.get().isEmpty()) {\n return Single.just(llmResponse);\n }\n\n Event callbackEvent = modelResponseEvent.toBuilder().content(llmResponse.content()).build();\n List callbacks = callbacksOpt.get();\n\n return Flowable.fromIterable(callbacks)\n .concatMapSingle(\n callback -> {\n CallbackContext callbackContext =\n new CallbackContext(context, callbackEvent.actions());\n return callback\n .call(callbackContext, llmResponse)\n .map(Optional::of)\n .defaultIfEmpty(Optional.empty());\n })\n .filter(Optional::isPresent)\n .firstElement()\n .map(Optional::get)\n .switchIfEmpty(Single.just(llmResponse));\n }\n\n /**\n * Executes a single iteration of the LLM flow: preprocessing → LLM call → postprocessing.\n *\n *

Handles early termination, LLM call limits, and agent transfer if needed.\n *\n * @return A {@link Flowable} of {@link Event} objects from this step.\n * @throws LlmCallsLimitExceededException if the agent exceeds allowed LLM invocations.\n * @throws IllegalStateException if a transfer agent is specified but not found.\n */\n private Flowable runOneStep(InvocationContext context) {\n LlmRequest initialLlmRequest = LlmRequest.builder().build();\n\n return preprocess(context, initialLlmRequest)\n .flatMapPublisher(\n preResult -> {\n LlmRequest llmRequestAfterPreprocess = preResult.updatedRequest();\n Iterable preEvents = preResult.events();\n\n if (context.endInvocation()) {\n logger.debug(\"End invocation requested during preprocessing.\");\n return Flowable.fromIterable(preEvents);\n }\n\n try {\n context.incrementLlmCallsCount();\n } catch (LlmCallsLimitExceededException e) {\n logger.error(\"LLM calls limit exceeded.\", e);\n return Flowable.fromIterable(preEvents).concatWith(Flowable.error(e));\n }\n\n final Event mutableEventTemplate =\n Event.builder()\n .id(Event.generateEventId())\n .invocationId(context.invocationId())\n .author(context.agent().name())\n .branch(context.branch())\n .build();\n\n Flowable restOfFlow =\n callLlm(context, llmRequestAfterPreprocess, mutableEventTemplate)\n .concatMap(\n llmResponse -> {\n Single postResultSingle =\n postprocess(\n context,\n mutableEventTemplate,\n llmRequestAfterPreprocess,\n llmResponse);\n\n return postResultSingle\n .doOnSuccess(\n ignored -> {\n String oldId = mutableEventTemplate.id();\n mutableEventTemplate.setId(Event.generateEventId());\n logger.debug(\n \"Updated mutableEventTemplate ID from {} to {} for next\"\n + \" LlmResponse\",\n oldId,\n mutableEventTemplate.id());\n })\n .toFlowable();\n })\n .concatMap(\n postResult -> {\n Flowable postProcessedEvents =\n Flowable.fromIterable(postResult.events());\n if (postResult.transferToAgent().isPresent()) {\n String agentToTransfer = postResult.transferToAgent().get();\n logger.debug(\"Transferring to agent: {}\", agentToTransfer);\n BaseAgent rootAgent = context.agent().rootAgent();\n BaseAgent nextAgent = rootAgent.findAgent(agentToTransfer);\n if (nextAgent == null) {\n String errorMsg =\n \"Agent not found for transfer: \" + agentToTransfer;\n logger.error(errorMsg);\n return postProcessedEvents.concatWith(\n Flowable.error(new IllegalStateException(errorMsg)));\n }\n return postProcessedEvents.concatWith(\n Flowable.defer(() -> nextAgent.runAsync(context)));\n }\n return postProcessedEvents;\n });\n\n return restOfFlow.startWithIterable(preEvents);\n });\n }\n\n /**\n * Executes the full LLM flow by repeatedly calling {@link #runOneStep} until a final response is\n * produced.\n *\n * @return A {@link Flowable} of all {@link Event}s generated during the flow.\n */\n @Override\n public Flowable run(InvocationContext invocationContext) {\n Flowable currentStepEvents = runOneStep(invocationContext).cache();\n if (++stepsCompleted >= maxSteps) {\n logger.debug(\"Ending flow execution because max steps reached.\");\n return currentStepEvents;\n }\n\n return currentStepEvents.concatWith(\n currentStepEvents\n .toList()\n .flatMapPublisher(\n eventList -> {\n if (eventList.isEmpty()\n || Iterables.getLast(eventList).finalResponse()\n || Iterables.getLast(eventList).actions().endInvocation().orElse(false)) {\n logger.debug(\n \"Ending flow execution based on final response, endInvocation action or\"\n + \" empty event list.\");\n return Flowable.empty();\n } else {\n logger.debug(\"Continuing to next step of the flow.\");\n return Flowable.defer(() -> run(invocationContext));\n }\n }));\n }\n\n /**\n * Executes the LLM flow in streaming mode.\n *\n *

Handles sending history and live requests to the LLM, receiving responses, processing them,\n * and managing agent transfers.\n *\n * @return A {@link Flowable} of {@link Event}s streamed in real-time.\n */\n @Override\n public Flowable runLive(InvocationContext invocationContext) {\n LlmRequest llmRequest = LlmRequest.builder().build();\n\n return preprocess(invocationContext, llmRequest)\n .flatMapPublisher(\n preResult -> {\n LlmRequest llmRequestAfterPreprocess = preResult.updatedRequest();\n if (invocationContext.endInvocation()) {\n return Flowable.fromIterable(preResult.events());\n }\n\n String eventIdForSendData = Event.generateEventId();\n LlmAgent agent = (LlmAgent) invocationContext.agent();\n BaseLlm llm =\n agent.resolvedModel().model().isPresent()\n ? agent.resolvedModel().model().get()\n : LlmRegistry.getLlm(agent.resolvedModel().modelName().get());\n BaseLlmConnection connection = llm.connect(llmRequestAfterPreprocess);\n Completable historySent =\n llmRequestAfterPreprocess.contents().isEmpty()\n ? Completable.complete()\n : Completable.defer(\n () -> {\n Span sendDataSpan =\n Telemetry.getTracer().spanBuilder(\"send_data\").startSpan();\n try (Scope scope = sendDataSpan.makeCurrent()) {\n return connection\n .sendHistory(llmRequestAfterPreprocess.contents())\n .doOnComplete(\n () -> {\n try (Scope innerScope = sendDataSpan.makeCurrent()) {\n Telemetry.traceSendData(\n invocationContext,\n eventIdForSendData,\n llmRequestAfterPreprocess.contents());\n }\n })\n .doOnError(\n error -> {\n sendDataSpan.setStatus(\n StatusCode.ERROR, error.getMessage());\n sendDataSpan.recordException(error);\n try (Scope innerScope = sendDataSpan.makeCurrent()) {\n Telemetry.traceSendData(\n invocationContext,\n eventIdForSendData,\n llmRequestAfterPreprocess.contents());\n }\n })\n .doFinally(sendDataSpan::end);\n }\n });\n\n Flowable liveRequests = invocationContext.liveRequestQueue().get().get();\n Disposable sendTask =\n historySent\n .observeOn(agent.executor().map(Schedulers::from).orElse(Schedulers.io()))\n .andThen(\n liveRequests\n .onBackpressureBuffer()\n .concatMapCompletable(\n request -> {\n if (request.content().isPresent()) {\n return connection.sendContent(request.content().get());\n } else if (request.blob().isPresent()) {\n return connection.sendRealtime(request.blob().get());\n }\n return Completable.fromAction(connection::close);\n }))\n .subscribeWith(\n new DisposableCompletableObserver() {\n @Override\n public void onComplete() {\n connection.close();\n }\n\n @Override\n public void onError(Throwable e) {\n connection.close(e);\n }\n });\n\n Event.Builder liveEventBuilderTemplate =\n Event.builder()\n .invocationId(invocationContext.invocationId())\n .author(invocationContext.agent().name())\n .branch(invocationContext.branch());\n\n Flowable receiveFlow =\n connection\n .receive()\n .flatMapSingle(\n llmResponse -> {\n Event baseEventForThisLlmResponse =\n liveEventBuilderTemplate.id(Event.generateEventId()).build();\n return postprocess(\n invocationContext,\n baseEventForThisLlmResponse,\n llmRequestAfterPreprocess,\n llmResponse);\n })\n .flatMap(\n postResult -> {\n Flowable events = Flowable.fromIterable(postResult.events());\n if (postResult.transferToAgent().isPresent()) {\n BaseAgent rootAgent = invocationContext.agent().rootAgent();\n BaseAgent nextAgent =\n rootAgent.findAgent(postResult.transferToAgent().get());\n if (nextAgent == null) {\n throw new IllegalStateException(\n \"Agent not found: \" + postResult.transferToAgent().get());\n }\n Flowable nextAgentEvents =\n nextAgent.runLive(invocationContext);\n events = Flowable.concat(events, nextAgentEvents);\n }\n return events;\n })\n .doOnNext(\n event -> {\n ImmutableList functionResponses =\n event.functionResponses();\n if (!functionResponses.isEmpty()) {\n invocationContext\n .liveRequestQueue()\n .get()\n .content(event.content().get());\n }\n if (functionResponses.stream()\n .anyMatch(\n functionResponse ->\n functionResponse\n .name()\n .orElse(\"\")\n .equals(\"transferToAgent\"))\n || event.actions().endInvocation().orElse(false)) {\n sendTask.dispose();\n connection.close();\n }\n });\n\n return receiveFlow\n .takeWhile(event -> !event.actions().endInvocation().orElse(false))\n .startWithIterable(preResult.events());\n });\n }\n\n /**\n * Builds an {@link Event} from LLM response, request, and base event data.\n *\n *

Populates the event with LLM output and tool function call metadata.\n *\n * @return A fully constructed {@link Event} representing the LLM response.\n */\n private Event buildModelResponseEvent(\n Event baseEventForLlmResponse, LlmRequest llmRequest, LlmResponse llmResponse) {\n Event.Builder eventBuilder =\n baseEventForLlmResponse.toBuilder()\n .content(llmResponse.content())\n .partial(llmResponse.partial())\n .errorCode(llmResponse.errorCode())\n .errorMessage(llmResponse.errorMessage())\n .interrupted(llmResponse.interrupted())\n .turnComplete(llmResponse.turnComplete())\n .groundingMetadata(llmResponse.groundingMetadata());\n\n Event event = eventBuilder.build();\n\n if (!event.functionCalls().isEmpty()) {\n Functions.populateClientFunctionCallId(event);\n Set longRunningToolIds =\n Functions.getLongRunningFunctionCalls(event.functionCalls(), llmRequest.tools());\n if (!longRunningToolIds.isEmpty()) {\n event.setLongRunningToolIds(Optional.of(longRunningToolIds));\n }\n }\n return event;\n }\n}\n"], ["/adk-java/contrib/langchain4j/src/main/java/com/google/adk/models/langchain4j/LangChain4j.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.google.adk.models.langchain4j;\n\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.google.adk.models.BaseLlm;\nimport com.google.adk.models.BaseLlmConnection;\nimport com.google.adk.models.LlmRequest;\nimport com.google.adk.models.LlmResponse;\nimport com.google.genai.types.Blob;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.FunctionCall;\nimport com.google.genai.types.FunctionCallingConfigMode;\nimport com.google.genai.types.FunctionDeclaration;\nimport com.google.genai.types.FunctionResponse;\nimport com.google.genai.types.GenerateContentConfig;\nimport com.google.genai.types.Part;\nimport com.google.genai.types.Schema;\nimport com.google.genai.types.ToolConfig;\nimport com.google.genai.types.Type;\nimport dev.langchain4j.Experimental;\nimport dev.langchain4j.agent.tool.ToolExecutionRequest;\nimport dev.langchain4j.agent.tool.ToolSpecification;\nimport dev.langchain4j.data.audio.Audio;\nimport dev.langchain4j.data.image.Image;\nimport dev.langchain4j.data.message.AiMessage;\nimport dev.langchain4j.data.message.AudioContent;\nimport dev.langchain4j.data.message.ChatMessage;\nimport dev.langchain4j.data.message.ImageContent;\nimport dev.langchain4j.data.message.PdfFileContent;\nimport dev.langchain4j.data.message.SystemMessage;\nimport dev.langchain4j.data.message.TextContent;\nimport dev.langchain4j.data.message.ToolExecutionResultMessage;\nimport dev.langchain4j.data.message.UserMessage;\nimport dev.langchain4j.data.message.VideoContent;\nimport dev.langchain4j.data.pdf.PdfFile;\nimport dev.langchain4j.data.video.Video;\nimport dev.langchain4j.exception.UnsupportedFeatureException;\nimport dev.langchain4j.model.chat.ChatModel;\nimport dev.langchain4j.model.chat.StreamingChatModel;\nimport dev.langchain4j.model.chat.request.ChatRequest;\nimport dev.langchain4j.model.chat.request.ToolChoice;\nimport dev.langchain4j.model.chat.request.json.JsonArraySchema;\nimport dev.langchain4j.model.chat.request.json.JsonBooleanSchema;\nimport dev.langchain4j.model.chat.request.json.JsonIntegerSchema;\nimport dev.langchain4j.model.chat.request.json.JsonNumberSchema;\nimport dev.langchain4j.model.chat.request.json.JsonObjectSchema;\nimport dev.langchain4j.model.chat.request.json.JsonSchemaElement;\nimport dev.langchain4j.model.chat.request.json.JsonStringSchema;\nimport dev.langchain4j.model.chat.response.ChatResponse;\nimport dev.langchain4j.model.chat.response.StreamingChatResponseHandler;\nimport io.reactivex.rxjava3.core.BackpressureStrategy;\nimport io.reactivex.rxjava3.core.Flowable;\nimport java.util.ArrayList;\nimport java.util.Base64;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.UUID;\n\n@Experimental\npublic class LangChain4j extends BaseLlm {\n\n private static final TypeReference> MAP_TYPE_REFERENCE =\n new TypeReference<>() {};\n\n private final ChatModel chatModel;\n private final StreamingChatModel streamingChatModel;\n private final ObjectMapper objectMapper;\n\n public LangChain4j(ChatModel chatModel) {\n super(\n Objects.requireNonNull(\n chatModel.defaultRequestParameters().modelName(), \"chat model name cannot be null\"));\n this.chatModel = Objects.requireNonNull(chatModel, \"chatModel cannot be null\");\n this.streamingChatModel = null;\n this.objectMapper = new ObjectMapper();\n }\n\n public LangChain4j(ChatModel chatModel, String modelName) {\n super(Objects.requireNonNull(modelName, \"chat model name cannot be null\"));\n this.chatModel = Objects.requireNonNull(chatModel, \"chatModel cannot be null\");\n this.streamingChatModel = null;\n this.objectMapper = new ObjectMapper();\n }\n\n public LangChain4j(StreamingChatModel streamingChatModel) {\n super(\n Objects.requireNonNull(\n streamingChatModel.defaultRequestParameters().modelName(),\n \"streaming chat model name cannot be null\"));\n this.chatModel = null;\n this.streamingChatModel =\n Objects.requireNonNull(streamingChatModel, \"streamingChatModel cannot be null\");\n this.objectMapper = new ObjectMapper();\n }\n\n public LangChain4j(StreamingChatModel streamingChatModel, String modelName) {\n super(Objects.requireNonNull(modelName, \"streaming chat model name cannot be null\"));\n this.chatModel = null;\n this.streamingChatModel =\n Objects.requireNonNull(streamingChatModel, \"streamingChatModel cannot be null\");\n this.objectMapper = new ObjectMapper();\n }\n\n public LangChain4j(ChatModel chatModel, StreamingChatModel streamingChatModel, String modelName) {\n super(Objects.requireNonNull(modelName, \"model name cannot be null\"));\n this.chatModel = Objects.requireNonNull(chatModel, \"chatModel cannot be null\");\n this.streamingChatModel =\n Objects.requireNonNull(streamingChatModel, \"streamingChatModel cannot be null\");\n this.objectMapper = new ObjectMapper();\n }\n\n @Override\n public Flowable generateContent(LlmRequest llmRequest, boolean stream) {\n if (stream) {\n if (this.streamingChatModel == null) {\n return Flowable.error(new IllegalStateException(\"StreamingChatModel is not configured\"));\n }\n\n ChatRequest chatRequest = toChatRequest(llmRequest);\n\n return Flowable.create(\n emitter -> {\n streamingChatModel.chat(\n chatRequest,\n new StreamingChatResponseHandler() {\n @Override\n public void onPartialResponse(String s) {\n emitter.onNext(\n LlmResponse.builder().content(Content.fromParts(Part.fromText(s))).build());\n }\n\n @Override\n public void onCompleteResponse(ChatResponse chatResponse) {\n if (chatResponse.aiMessage().hasToolExecutionRequests()) {\n AiMessage aiMessage = chatResponse.aiMessage();\n toParts(aiMessage).stream()\n .map(Part::functionCall)\n .forEach(\n functionCall -> {\n functionCall.ifPresent(\n function -> {\n emitter.onNext(\n LlmResponse.builder()\n .content(\n Content.fromParts(\n Part.fromFunctionCall(\n function.name().orElse(\"\"),\n function.args().orElse(Map.of()))))\n .build());\n });\n });\n }\n emitter.onComplete();\n }\n\n @Override\n public void onError(Throwable throwable) {\n emitter.onError(throwable);\n }\n });\n },\n BackpressureStrategy.BUFFER);\n } else {\n if (this.chatModel == null) {\n return Flowable.error(new IllegalStateException(\"ChatModel is not configured\"));\n }\n\n ChatRequest chatRequest = toChatRequest(llmRequest);\n ChatResponse chatResponse = chatModel.chat(chatRequest);\n LlmResponse llmResponse = toLlmResponse(chatResponse);\n\n return Flowable.just(llmResponse);\n }\n }\n\n private ChatRequest toChatRequest(LlmRequest llmRequest) {\n ChatRequest.Builder requestBuilder = ChatRequest.builder();\n\n List toolSpecifications = toToolSpecifications(llmRequest);\n requestBuilder.toolSpecifications(toolSpecifications);\n\n if (llmRequest.config().isPresent()) {\n GenerateContentConfig generateContentConfig = llmRequest.config().get();\n\n generateContentConfig\n .temperature()\n .ifPresent(temp -> requestBuilder.temperature(temp.doubleValue()));\n generateContentConfig.topP().ifPresent(topP -> requestBuilder.topP(topP.doubleValue()));\n generateContentConfig.topK().ifPresent(topK -> requestBuilder.topK(topK.intValue()));\n generateContentConfig.maxOutputTokens().ifPresent(requestBuilder::maxOutputTokens);\n generateContentConfig.stopSequences().ifPresent(requestBuilder::stopSequences);\n generateContentConfig\n .frequencyPenalty()\n .ifPresent(freqPenalty -> requestBuilder.frequencyPenalty(freqPenalty.doubleValue()));\n generateContentConfig\n .presencePenalty()\n .ifPresent(presPenalty -> requestBuilder.presencePenalty(presPenalty.doubleValue()));\n\n if (generateContentConfig.toolConfig().isPresent()) {\n ToolConfig toolConfig = generateContentConfig.toolConfig().get();\n toolConfig\n .functionCallingConfig()\n .ifPresent(\n functionCallingConfig -> {\n functionCallingConfig\n .mode()\n .ifPresent(\n functionMode -> {\n if (functionMode\n .knownEnum()\n .equals(FunctionCallingConfigMode.Known.AUTO)) {\n requestBuilder.toolChoice(ToolChoice.AUTO);\n } else if (functionMode\n .knownEnum()\n .equals(FunctionCallingConfigMode.Known.ANY)) {\n // TODO check if it's the correct\n // mapping\n requestBuilder.toolChoice(ToolChoice.REQUIRED);\n functionCallingConfig\n .allowedFunctionNames()\n .ifPresent(\n allowedFunctionNames -> {\n requestBuilder.toolSpecifications(\n toolSpecifications.stream()\n .filter(\n toolSpecification ->\n allowedFunctionNames.contains(\n toolSpecification.name()))\n .toList());\n });\n } else if (functionMode\n .knownEnum()\n .equals(FunctionCallingConfigMode.Known.NONE)) {\n requestBuilder.toolSpecifications(List.of());\n }\n });\n });\n toolConfig\n .retrievalConfig()\n .ifPresent(\n retrievalConfig -> {\n // TODO? It exposes Latitude / Longitude, what to do with this?\n });\n }\n }\n\n return requestBuilder.messages(toMessages(llmRequest)).build();\n }\n\n private List toMessages(LlmRequest llmRequest) {\n List messages =\n new ArrayList<>(\n llmRequest.getSystemInstructions().stream().map(SystemMessage::from).toList());\n llmRequest.contents().forEach(content -> messages.addAll(toChatMessage(content)));\n return messages;\n }\n\n private List toChatMessage(Content content) {\n String role = content.role().orElseThrow().toLowerCase();\n return switch (role) {\n case \"user\" -> toUserOrToolResultMessage(content);\n case \"model\", \"assistant\" -> List.of(toAiMessage(content));\n default -> throw new IllegalStateException(\"Unexpected role: \" + role);\n };\n }\n\n private List toUserOrToolResultMessage(Content content) {\n List toolExecutionResultMessages = new ArrayList<>();\n List toolExecutionRequests = new ArrayList<>();\n\n List lc4jContents = new ArrayList<>();\n\n for (Part part : content.parts().orElse(List.of())) {\n if (part.text().isPresent()) {\n lc4jContents.add(TextContent.from(part.text().get()));\n } else if (part.functionResponse().isPresent()) {\n FunctionResponse functionResponse = part.functionResponse().get();\n toolExecutionResultMessages.add(\n ToolExecutionResultMessage.from(\n functionResponse.id().orElseThrow(),\n functionResponse.name().orElseThrow(),\n toJson(functionResponse.response().orElseThrow())));\n } else if (part.functionCall().isPresent()) {\n FunctionCall functionCall = part.functionCall().get();\n toolExecutionRequests.add(\n ToolExecutionRequest.builder()\n .id(functionCall.id().orElseThrow())\n .name(functionCall.name().orElseThrow())\n .arguments(toJson(functionCall.args().orElse(Map.of())))\n .build());\n } else if (part.inlineData().isPresent()) {\n Blob blob = part.inlineData().get();\n\n if (blob.mimeType().isEmpty() || blob.data().isEmpty()) {\n throw new IllegalArgumentException(\"Mime type and data required\");\n }\n\n byte[] bytes = blob.data().get();\n String mimeType = blob.mimeType().get();\n\n Base64.Encoder encoder = Base64.getEncoder();\n\n dev.langchain4j.data.message.Content lc4jContent = null;\n\n if (mimeType.startsWith(\"audio/\")) {\n lc4jContent =\n AudioContent.from(\n Audio.builder()\n .base64Data(encoder.encodeToString(bytes))\n .mimeType(mimeType)\n .build());\n } else if (mimeType.startsWith(\"video/\")) {\n lc4jContent =\n VideoContent.from(\n Video.builder()\n .base64Data(encoder.encodeToString(bytes))\n .mimeType(mimeType)\n .build());\n } else if (mimeType.startsWith(\"image/\")) {\n lc4jContent =\n ImageContent.from(\n Image.builder()\n .base64Data(encoder.encodeToString(bytes))\n .mimeType(mimeType)\n .build());\n } else if (mimeType.startsWith(\"application/pdf\")) {\n lc4jContent =\n PdfFileContent.from(\n PdfFile.builder()\n .base64Data(encoder.encodeToString(bytes))\n .mimeType(mimeType)\n .build());\n } else if (mimeType.startsWith(\"text/\")\n || mimeType.equals(\"application/json\")\n || mimeType.endsWith(\"+json\")\n || mimeType.endsWith(\"+xml\")) {\n // TODO are there missing text based mime types?\n // TODO should we assume UTF_8?\n lc4jContents.add(\n TextContent.from(new String(bytes, java.nio.charset.StandardCharsets.UTF_8)));\n }\n\n if (lc4jContent != null) {\n lc4jContents.add(lc4jContent);\n } else {\n throw new IllegalArgumentException(\"Unknown or unhandled mime type: \" + mimeType);\n }\n } else {\n throw new IllegalStateException(\n \"Text, media or functionCall is expected, but was: \" + part);\n }\n }\n\n if (!toolExecutionResultMessages.isEmpty()) {\n return new ArrayList(toolExecutionResultMessages);\n } else if (!toolExecutionRequests.isEmpty()) {\n return toolExecutionRequests.stream()\n .map(AiMessage::aiMessage)\n .map(msg -> (ChatMessage) msg)\n .toList();\n } else {\n return List.of(UserMessage.from(lc4jContents));\n }\n }\n\n private AiMessage toAiMessage(Content content) {\n List texts = new ArrayList<>();\n List toolExecutionRequests = new ArrayList<>();\n\n content\n .parts()\n .orElse(List.of())\n .forEach(\n part -> {\n if (part.text().isPresent()) {\n texts.add(part.text().get());\n } else if (part.functionCall().isPresent()) {\n FunctionCall functionCall = part.functionCall().get();\n ToolExecutionRequest toolExecutionRequest =\n ToolExecutionRequest.builder()\n .id(functionCall.id().orElseThrow())\n .name(functionCall.name().orElseThrow())\n .arguments(toJson(functionCall.args().orElseThrow()))\n .build();\n toolExecutionRequests.add(toolExecutionRequest);\n } else {\n throw new IllegalStateException(\n \"Either text or functionCall is expected, but was: \" + part);\n }\n });\n\n return AiMessage.builder()\n .text(String.join(\"\\n\", texts))\n .toolExecutionRequests(toolExecutionRequests)\n .build();\n }\n\n private String toJson(Object object) {\n try {\n return objectMapper.writeValueAsString(object);\n } catch (JsonProcessingException e) {\n throw new RuntimeException(e);\n }\n }\n\n private List toToolSpecifications(LlmRequest llmRequest) {\n List toolSpecifications = new ArrayList<>();\n\n llmRequest\n .tools()\n .values()\n .forEach(\n baseTool -> {\n if (baseTool.declaration().isPresent()) {\n FunctionDeclaration functionDeclaration = baseTool.declaration().get();\n if (functionDeclaration.parameters().isPresent()) {\n Schema schema = functionDeclaration.parameters().get();\n ToolSpecification toolSpecification =\n ToolSpecification.builder()\n .name(baseTool.name())\n .description(baseTool.description())\n .parameters(toParameters(schema))\n .build();\n toolSpecifications.add(toolSpecification);\n } else {\n // TODO exception or something else?\n throw new IllegalStateException(\"Tool lacking parameters: \" + baseTool);\n }\n } else {\n // TODO exception or something else?\n throw new IllegalStateException(\"Tool lacking declaration: \" + baseTool);\n }\n });\n\n return toolSpecifications;\n }\n\n private JsonObjectSchema toParameters(Schema schema) {\n if (schema.type().isPresent() && schema.type().get().knownEnum().equals(Type.Known.OBJECT)) {\n return JsonObjectSchema.builder()\n .addProperties(toProperties(schema))\n .required(schema.required().orElse(List.of()))\n .build();\n } else {\n throw new UnsupportedOperationException(\n \"LangChain4jLlm does not support schema of type: \" + schema.type());\n }\n }\n\n private Map toProperties(Schema schema) {\n Map properties = schema.properties().orElse(Map.of());\n Map result = new HashMap<>();\n properties.forEach((k, v) -> result.put(k, toJsonSchemaElement(v)));\n return result;\n }\n\n private JsonSchemaElement toJsonSchemaElement(Schema schema) {\n if (schema != null && schema.type().isPresent()) {\n Type type = schema.type().get();\n return switch (type.knownEnum()) {\n case STRING ->\n JsonStringSchema.builder().description(schema.description().orElse(null)).build();\n case NUMBER ->\n JsonNumberSchema.builder().description(schema.description().orElse(null)).build();\n case INTEGER ->\n JsonIntegerSchema.builder().description(schema.description().orElse(null)).build();\n case BOOLEAN ->\n JsonBooleanSchema.builder().description(schema.description().orElse(null)).build();\n case ARRAY ->\n JsonArraySchema.builder()\n .description(schema.description().orElse(null))\n .items(toJsonSchemaElement(schema.items().orElseThrow()))\n .build();\n case OBJECT -> toParameters(schema);\n case TYPE_UNSPECIFIED ->\n throw new UnsupportedFeatureException(\n \"LangChain4jLlm does not support schema of type: \" + type);\n };\n } else {\n throw new IllegalArgumentException(\"Schema type cannot be null or absent\");\n }\n }\n\n private LlmResponse toLlmResponse(ChatResponse chatResponse) {\n Content content =\n Content.builder().role(\"model\").parts(toParts(chatResponse.aiMessage())).build();\n\n return LlmResponse.builder().content(content).build();\n }\n\n private List toParts(AiMessage aiMessage) {\n if (aiMessage.hasToolExecutionRequests()) {\n List parts = new ArrayList<>();\n aiMessage\n .toolExecutionRequests()\n .forEach(\n toolExecutionRequest -> {\n FunctionCall functionCall =\n FunctionCall.builder()\n .id(\n toolExecutionRequest.id() != null\n ? toolExecutionRequest.id()\n : UUID.randomUUID().toString())\n .name(toolExecutionRequest.name())\n .args(toArgs(toolExecutionRequest))\n .build();\n Part part = Part.builder().functionCall(functionCall).build();\n parts.add(part);\n });\n return parts;\n } else {\n Part part = Part.builder().text(aiMessage.text()).build();\n return List.of(part);\n }\n }\n\n private Map toArgs(ToolExecutionRequest toolExecutionRequest) {\n try {\n return objectMapper.readValue(toolExecutionRequest.arguments(), MAP_TYPE_REFERENCE);\n } catch (JsonProcessingException e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public BaseLlmConnection connect(LlmRequest llmRequest) {\n throw new UnsupportedOperationException(\n \"Live connection is not supported for LangChain4j models.\");\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/models/Claude.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.models;\n\nimport com.anthropic.client.AnthropicClient;\nimport com.anthropic.models.messages.ContentBlock;\nimport com.anthropic.models.messages.ContentBlockParam;\nimport com.anthropic.models.messages.Message;\nimport com.anthropic.models.messages.MessageCreateParams;\nimport com.anthropic.models.messages.MessageParam;\nimport com.anthropic.models.messages.MessageParam.Role;\nimport com.anthropic.models.messages.TextBlockParam;\nimport com.anthropic.models.messages.Tool;\nimport com.anthropic.models.messages.ToolChoice;\nimport com.anthropic.models.messages.ToolChoiceAuto;\nimport com.anthropic.models.messages.ToolResultBlockParam;\nimport com.anthropic.models.messages.ToolUnion;\nimport com.anthropic.models.messages.ToolUseBlockParam;\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.fasterxml.jackson.datatype.jdk8.Jdk8Module;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.FunctionCall;\nimport com.google.genai.types.FunctionDeclaration;\nimport com.google.genai.types.GenerateContentConfig;\nimport com.google.genai.types.Part;\nimport io.reactivex.rxjava3.core.Flowable;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.Optional;\nimport java.util.stream.Collectors;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * Represents the Claude Generative AI model by Anthropic.\n *\n *

This class provides methods for interacting with Claude models. Streaming and live connections\n * are not currently supported for Claude.\n */\npublic class Claude extends BaseLlm {\n\n private static final Logger logger = LoggerFactory.getLogger(Claude.class);\n private static final int MAX_TOKEN = 8192;\n private final AnthropicClient anthropicClient;\n\n /**\n * Constructs a new Claude instance.\n *\n * @param modelName The name of the Claude model to use (e.g., \"claude-3-opus-20240229\").\n * @param anthropicClient The Anthropic API client instance.\n */\n public Claude(String modelName, AnthropicClient anthropicClient) {\n super(modelName);\n this.anthropicClient = anthropicClient;\n }\n\n @Override\n public Flowable generateContent(LlmRequest llmRequest, boolean stream) {\n // TODO: Switch to streaming API.\n List messages =\n llmRequest.contents().stream()\n .map(this::contentToAnthropicMessageParam)\n .collect(Collectors.toList());\n\n List tools = ImmutableList.of();\n if (llmRequest.config().isPresent()\n && llmRequest.config().get().tools().isPresent()\n && !llmRequest.config().get().tools().get().isEmpty()\n && llmRequest.config().get().tools().get().get(0).functionDeclarations().isPresent()) {\n tools =\n llmRequest.config().get().tools().get().get(0).functionDeclarations().get().stream()\n .map(this::functionDeclarationToAnthropicTool)\n .map(tool -> ToolUnion.ofTool(tool))\n .collect(Collectors.toList());\n }\n\n ToolChoice toolChoice =\n llmRequest.tools().isEmpty()\n ? null\n : ToolChoice.ofAuto(ToolChoiceAuto.builder().disableParallelToolUse(true).build());\n\n String systemText = \"\";\n Optional configOpt = llmRequest.config();\n if (configOpt.isPresent()) {\n Optional systemInstructionOpt = configOpt.get().systemInstruction();\n if (systemInstructionOpt.isPresent()) {\n String extractedSystemText =\n systemInstructionOpt.get().parts().orElse(ImmutableList.of()).stream()\n .filter(p -> p.text().isPresent())\n .map(p -> p.text().get())\n .collect(Collectors.joining(\"\\n\"));\n if (!extractedSystemText.isEmpty()) {\n systemText = extractedSystemText;\n }\n }\n }\n\n var message =\n this.anthropicClient\n .messages()\n .create(\n MessageCreateParams.builder()\n .model(llmRequest.model().orElse(model()))\n .system(systemText)\n .messages(messages)\n .tools(tools)\n .toolChoice(toolChoice)\n .maxTokens(MAX_TOKEN)\n .build());\n\n logger.debug(\"Claude response: {}\", message);\n\n return Flowable.just(convertAnthropicResponseToLlmResponse(message));\n }\n\n private Role toClaudeRole(String role) {\n return role.equals(\"model\") || role.equals(\"assistant\") ? Role.ASSISTANT : Role.USER;\n }\n\n private MessageParam contentToAnthropicMessageParam(Content content) {\n return MessageParam.builder()\n .role(toClaudeRole(content.role().orElse(\"\")))\n .contentOfBlockParams(\n content.parts().orElse(ImmutableList.of()).stream()\n .map(this::partToAnthropicMessageBlock)\n .filter(Objects::nonNull)\n .collect(Collectors.toList()))\n .build();\n }\n\n private ContentBlockParam partToAnthropicMessageBlock(Part part) {\n if (part.text().isPresent()) {\n return ContentBlockParam.ofText(TextBlockParam.builder().text(part.text().get()).build());\n } else if (part.functionCall().isPresent()) {\n return ContentBlockParam.ofToolUse(\n ToolUseBlockParam.builder()\n .id(part.functionCall().get().id().orElse(\"\"))\n .name(part.functionCall().get().name().orElseThrow())\n .type(com.anthropic.core.JsonValue.from(\"tool_use\"))\n .input(\n com.anthropic.core.JsonValue.from(\n part.functionCall().get().args().orElse(ImmutableMap.of())))\n .build());\n } else if (part.functionResponse().isPresent()) {\n String content = \"\";\n if (part.functionResponse().get().response().isPresent()\n && part.functionResponse().get().response().get().getOrDefault(\"result\", null) != null) {\n content = part.functionResponse().get().response().get().get(\"result\").toString();\n }\n return ContentBlockParam.ofToolResult(\n ToolResultBlockParam.builder()\n .toolUseId(part.functionResponse().get().id().orElse(\"\"))\n .content(content)\n .isError(false)\n .build());\n }\n throw new UnsupportedOperationException(\"Not supported yet.\");\n }\n\n private void updateTypeString(Map valueDict) {\n if (valueDict == null) {\n return;\n }\n if (valueDict.containsKey(\"type\")) {\n valueDict.put(\"type\", ((String) valueDict.get(\"type\")).toLowerCase());\n }\n\n if (valueDict.containsKey(\"items\")) {\n updateTypeString((Map) valueDict.get(\"items\"));\n\n if (valueDict.get(\"items\") instanceof Map\n && ((Map) valueDict.get(\"items\")).containsKey(\"properties\")) {\n Map properties =\n (Map) ((Map) valueDict.get(\"items\")).get(\"properties\");\n if (properties != null) {\n for (Object value : properties.values()) {\n if (value instanceof Map) {\n updateTypeString((Map) value);\n }\n }\n }\n }\n }\n }\n\n private Tool functionDeclarationToAnthropicTool(FunctionDeclaration functionDeclaration) {\n Map> properties = new HashMap<>();\n if (functionDeclaration.parameters().isPresent()\n && functionDeclaration.parameters().get().properties().isPresent()) {\n functionDeclaration\n .parameters()\n .get()\n .properties()\n .get()\n .forEach(\n (key, schema) -> {\n ObjectMapper objectMapper = new ObjectMapper();\n objectMapper.registerModule(new Jdk8Module());\n Map schemaMap =\n objectMapper.convertValue(schema, new TypeReference>() {});\n updateTypeString(schemaMap);\n properties.put(key, schemaMap);\n });\n }\n\n return Tool.builder()\n .name(functionDeclaration.name().orElseThrow())\n .description(functionDeclaration.description().orElse(\"\"))\n .inputSchema(\n Tool.InputSchema.builder()\n .properties(com.anthropic.core.JsonValue.from(properties))\n .build())\n .build();\n }\n\n private LlmResponse convertAnthropicResponseToLlmResponse(Message message) {\n LlmResponse.Builder responseBuilder = LlmResponse.builder();\n List parts = new ArrayList<>();\n\n if (message.content() != null) {\n for (ContentBlock block : message.content()) {\n Part part = anthropicContentBlockToPart(block);\n if (part != null) {\n parts.add(part);\n }\n }\n responseBuilder.content(\n Content.builder().role(\"model\").parts(ImmutableList.copyOf(parts)).build());\n }\n return responseBuilder.build();\n }\n\n private Part anthropicContentBlockToPart(ContentBlock block) {\n if (block.isText()) {\n return Part.builder().text(block.asText().text()).build();\n } else if (block.isToolUse()) {\n return Part.builder()\n .functionCall(\n FunctionCall.builder()\n .id(block.asToolUse().id())\n .name(block.asToolUse().name())\n .args(\n block\n .asToolUse()\n ._input()\n .convert(new TypeReference>() {}))\n .build())\n .build();\n }\n throw new UnsupportedOperationException(\"Not supported yet.\");\n }\n\n @Override\n public BaseLlmConnection connect(LlmRequest llmRequest) {\n throw new UnsupportedOperationException(\"Live connection is not supported for Claude models.\");\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/llmflows/Contents.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows.llmflows;\n\nimport static com.google.common.collect.ImmutableList.toImmutableList;\n\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.google.adk.JsonBaseModel;\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.agents.LlmAgent;\nimport com.google.adk.events.Event;\nimport com.google.adk.models.LlmRequest;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Iterables;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.FunctionCall;\nimport com.google.genai.types.FunctionResponse;\nimport com.google.genai.types.Part;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.Set;\n\n/** {@link RequestProcessor} that populates content in request for LLM flows. */\npublic final class Contents implements RequestProcessor {\n public Contents() {}\n\n @Override\n public Single processRequest(\n InvocationContext context, LlmRequest request) {\n if (!(context.agent() instanceof LlmAgent)) {\n return Single.just(\n RequestProcessor.RequestProcessingResult.create(request, context.session().events()));\n }\n LlmAgent llmAgent = (LlmAgent) context.agent();\n\n if (llmAgent.includeContents() == LlmAgent.IncludeContents.NONE) {\n return Single.just(\n RequestProcessor.RequestProcessingResult.create(\n request.toBuilder().contents(ImmutableList.of()).build(), ImmutableList.of()));\n }\n\n ImmutableList contents =\n getContents(context.branch(), context.session().events(), context.agent().name());\n\n return Single.just(\n RequestProcessor.RequestProcessingResult.create(\n request.toBuilder().contents(contents).build(), ImmutableList.of()));\n }\n\n private ImmutableList getContents(\n Optional currentBranch, List events, String agentName) {\n List filteredEvents = new ArrayList<>();\n\n // Filter the events, leaving the contents and the function calls and responses from the current\n // agent.\n for (Event event : events) {\n // Skip events without content, or generated neither by user nor by model or has empty text.\n // E.g. events purely for mutating session states.\n if (event.content().isEmpty()) {\n continue;\n }\n var content = event.content().get();\n if (content.role().isEmpty()\n || content.role().get().isEmpty()\n || content.parts().isEmpty()\n || content.parts().get().isEmpty()\n || content.parts().get().get(0).text().map(String::isEmpty).orElse(false)) {\n continue;\n }\n\n if (!isEventBelongsToBranch(currentBranch, event)) {\n continue;\n }\n\n // TODO: Skip auth events.\n\n if (isOtherAgentReply(agentName, event)) {\n filteredEvents.add(convertForeignEvent(event));\n } else {\n filteredEvents.add(event);\n }\n }\n\n List resultEvents = rearrangeEventsForLatestFunctionResponse(filteredEvents);\n resultEvents = rearrangeEventsForAsyncFunctionResponsesInHistory(resultEvents);\n\n return resultEvents.stream()\n .map(Event::content)\n .flatMap(Optional::stream)\n .collect(toImmutableList());\n }\n\n /** Whether the event is a reply from another agent. */\n private static boolean isOtherAgentReply(String agentName, Event event) {\n return !agentName.isEmpty()\n && !event.author().equals(agentName)\n && !event.author().equals(\"user\");\n }\n\n /** Converts an {@code event} authored by another agent to a 'contextual-only' event. */\n private static Event convertForeignEvent(Event event) {\n if (event.content().isEmpty()\n || event.content().get().parts().isEmpty()\n || event.content().get().parts().get().isEmpty()) {\n return event;\n }\n\n List parts = new ArrayList<>();\n parts.add(Part.fromText(\"For context:\"));\n\n String originalAuthor = event.author();\n\n for (Part part : event.content().get().parts().get()) {\n if (part.text().isPresent() && !part.text().get().isEmpty()) {\n parts.add(Part.fromText(String.format(\"[%s] said: %s\", originalAuthor, part.text().get())));\n } else if (part.functionCall().isPresent()) {\n FunctionCall functionCall = part.functionCall().get();\n parts.add(\n Part.fromText(\n String.format(\n \"[%s] called tool `%s` with parameters: %s\",\n originalAuthor,\n functionCall.name().orElse(\"unknown_tool\"),\n functionCall.args().map(Contents::convertMapToJson).orElse(\"{}\"))));\n } else if (part.functionResponse().isPresent()) {\n FunctionResponse functionResponse = part.functionResponse().get();\n parts.add(\n Part.fromText(\n String.format(\n \"[%s] `%s` tool returned result: %s\",\n originalAuthor,\n functionResponse.name().orElse(\"unknown_tool\"),\n functionResponse.response().map(Contents::convertMapToJson).orElse(\"{}\"))));\n } else {\n parts.add(part);\n }\n }\n\n Content content = Content.builder().role(\"user\").parts(parts).build();\n return event.toBuilder().author(\"user\").content(content).build();\n }\n\n private static String convertMapToJson(Map struct) {\n try {\n return JsonBaseModel.getMapper().writeValueAsString(struct);\n } catch (JsonProcessingException e) {\n throw new IllegalStateException(\"Failed to serialize the object to JSON.\", e);\n }\n }\n\n private static boolean isEventBelongsToBranch(Optional invocationBranchOpt, Event event) {\n Optional eventBranchOpt = event.branch();\n\n if (invocationBranchOpt.isEmpty() || invocationBranchOpt.get().isEmpty()) {\n return true;\n }\n if (eventBranchOpt.isEmpty() || eventBranchOpt.get().isEmpty()) {\n return true;\n }\n return invocationBranchOpt.get().startsWith(eventBranchOpt.get());\n }\n\n /**\n * Rearranges the events for the latest function response. If the latest function response is for\n * an async function call, all events between the initial function call and the latest function\n * response will be removed.\n *\n * @param events The list of events.\n * @return A new list of events with the appropriate rearrangement.\n */\n private static List rearrangeEventsForLatestFunctionResponse(List events) {\n // TODO: b/412663475 - Handle parallel function calls within the same event. Currently, this\n // throws an error.\n if (events.isEmpty() || Iterables.getLast(events).functionResponses().isEmpty()) {\n // No need to process if the list is empty or the last event is not a function response\n return events;\n }\n\n Event latestEvent = Iterables.getLast(events);\n // Extract function response IDs from the latest event\n Set functionResponseIds = new HashSet<>();\n latestEvent\n .content()\n .flatMap(Content::parts)\n .ifPresent(\n parts -> {\n for (Part part : parts) {\n part.functionResponse()\n .flatMap(FunctionResponse::id)\n .ifPresent(functionResponseIds::add);\n }\n });\n\n if (functionResponseIds.isEmpty()) {\n return events;\n }\n\n // Check if the second to last event contains the corresponding function call\n if (events.size() >= 2) {\n Event penultimateEvent = events.get(events.size() - 2);\n boolean matchFound =\n penultimateEvent\n .content()\n .flatMap(Content::parts)\n .map(\n parts -> {\n for (Part part : parts) {\n if (part.functionCall()\n .flatMap(FunctionCall::id)\n .map(functionResponseIds::contains)\n .orElse(false)) {\n return true; // Found a matching function call ID\n }\n }\n return false;\n })\n .orElse(false);\n if (matchFound) {\n // The latest function response is already matched with the immediately preceding event\n return events;\n }\n }\n\n // Look for the corresponding function call event by iterating backwards\n int functionCallEventIndex = -1;\n for (int i = events.size() - 3; i >= 0; i--) { // Start from third-to-last\n Event event = events.get(i);\n Optional> partsOptional = event.content().flatMap(Content::parts);\n if (partsOptional.isPresent()) {\n List parts = partsOptional.get();\n for (Part part : parts) {\n Optional callIdOpt = part.functionCall().flatMap(FunctionCall::id);\n if (callIdOpt.isPresent() && functionResponseIds.contains(callIdOpt.get())) {\n functionCallEventIndex = i;\n // Add all function call IDs from this event to the set\n parts.forEach(\n p ->\n p.functionCall().flatMap(FunctionCall::id).ifPresent(functionResponseIds::add));\n break; // Found the matching event\n }\n }\n }\n if (functionCallEventIndex != -1) {\n break; // Exit outer loop once found\n }\n }\n\n if (functionCallEventIndex == -1) {\n if (!functionResponseIds.isEmpty()) {\n throw new IllegalStateException(\n \"No function call event found for function response IDs: \" + functionResponseIds);\n } else {\n return events; // No IDs to match, no rearrangement based on this logic.\n }\n }\n\n List resultEvents = new ArrayList<>(events.subList(0, functionCallEventIndex + 1));\n\n // Collect all function response events between the call and the latest response\n List functionResponseEventsToMerge = new ArrayList<>();\n for (int i = functionCallEventIndex + 1; i < events.size() - 1; i++) {\n Event intermediateEvent = events.get(i);\n boolean hasMatchingResponse =\n intermediateEvent\n .content()\n .flatMap(Content::parts)\n .map(\n parts -> {\n for (Part part : parts) {\n if (part.functionResponse()\n .flatMap(FunctionResponse::id)\n .map(functionResponseIds::contains)\n .orElse(false)) {\n return true;\n }\n }\n return false;\n })\n .orElse(false);\n if (hasMatchingResponse) {\n functionResponseEventsToMerge.add(intermediateEvent);\n }\n }\n functionResponseEventsToMerge.add(latestEvent);\n\n if (!functionResponseEventsToMerge.isEmpty()) {\n resultEvents.add(mergeFunctionResponseEvents(functionResponseEventsToMerge));\n }\n\n return resultEvents;\n }\n\n private static List rearrangeEventsForAsyncFunctionResponsesInHistory(List events) {\n Map functionCallIdToResponseEventIndex = new HashMap<>();\n for (int i = 0; i < events.size(); i++) {\n final int index = i;\n Event event = events.get(index);\n event\n .content()\n .flatMap(Content::parts)\n .ifPresent(\n parts -> {\n for (Part part : parts) {\n part.functionResponse()\n .ifPresent(\n response ->\n response\n .id()\n .ifPresent(\n functionCallId ->\n functionCallIdToResponseEventIndex.put(\n functionCallId, index)));\n }\n });\n }\n\n List resultEvents = new ArrayList<>();\n // Keep track of response events already added to avoid duplicates when merging\n Set processedResponseIndices = new HashSet<>();\n\n for (int i = 0; i < events.size(); i++) {\n Event event = events.get(i);\n\n // Skip response events that have already been processed and added alongside their call event\n if (processedResponseIndices.contains(i)) {\n continue;\n }\n\n Optional> partsOptional = event.content().flatMap(Content::parts);\n boolean hasFunctionCalls =\n partsOptional\n .map(parts -> parts.stream().anyMatch(p -> p.functionCall().isPresent()))\n .orElse(false);\n\n if (hasFunctionCalls) {\n Set responseEventIndices = new HashSet<>();\n // Iterate through parts again to get function call IDs\n partsOptional\n .get()\n .forEach(\n part ->\n part.functionCall()\n .ifPresent(\n call ->\n call.id()\n .ifPresent(\n functionCallId -> {\n if (functionCallIdToResponseEventIndex.containsKey(\n functionCallId)) {\n responseEventIndices.add(\n functionCallIdToResponseEventIndex.get(\n functionCallId));\n }\n })));\n\n resultEvents.add(event); // Add the function call event\n\n if (!responseEventIndices.isEmpty()) {\n List responseEventsToAdd = new ArrayList<>();\n List sortedIndices = new ArrayList<>(responseEventIndices);\n Collections.sort(sortedIndices); // Process in chronological order\n\n for (int index : sortedIndices) {\n if (processedResponseIndices.add(index)) { // Add index and check if it was newly added\n responseEventsToAdd.add(events.get(index));\n }\n }\n\n if (responseEventsToAdd.size() == 1) {\n resultEvents.add(responseEventsToAdd.get(0));\n } else if (responseEventsToAdd.size() > 1) {\n resultEvents.add(mergeFunctionResponseEvents(responseEventsToAdd));\n }\n }\n } else {\n resultEvents.add(event);\n }\n }\n\n return resultEvents;\n }\n\n /**\n * Merges a list of function response events into one event.\n *\n *

The key goal is to ensure: 1. functionCall and functionResponse are always of the same\n * number. 2. The functionCall and functionResponse are consecutively in the content.\n *\n * @param functionResponseEvents A list of function response events. NOTE: functionResponseEvents\n * must fulfill these requirements: 1. The list is in increasing order of timestamp; 2. the\n * first event is the initial function response event; 3. all later events should contain at\n * least one function response part that related to the function call event. Caveat: This\n * implementation doesn't support when a parallel function call event contains async function\n * call of the same name.\n * @return A merged event, that is 1. All later function_response will replace function response\n * part in the initial function response event. 2. All non-function response parts will be\n * appended to the part list of the initial function response event.\n */\n private static Event mergeFunctionResponseEvents(List functionResponseEvents) {\n if (functionResponseEvents.isEmpty()) {\n throw new IllegalArgumentException(\"At least one functionResponse event is required.\");\n }\n if (functionResponseEvents.size() == 1) {\n return functionResponseEvents.get(0);\n }\n\n Event baseEvent = functionResponseEvents.get(0);\n Content baseContent =\n baseEvent\n .content()\n .orElseThrow(() -> new IllegalArgumentException(\"Base event must have content.\"));\n List baseParts =\n baseContent\n .parts()\n .orElseThrow(() -> new IllegalArgumentException(\"Base event content must have parts.\"));\n\n if (baseParts.isEmpty()) {\n throw new IllegalArgumentException(\n \"There should be at least one functionResponse part in the base event.\");\n }\n List partsInMergedEvent = new ArrayList<>(baseParts);\n\n Map partIndicesInMergedEvent = new HashMap<>();\n for (int i = 0; i < partsInMergedEvent.size(); i++) {\n final int index = i;\n Part part = partsInMergedEvent.get(i);\n if (part.functionResponse().isPresent()) {\n part.functionResponse()\n .get()\n .id()\n .ifPresent(functionCallId -> partIndicesInMergedEvent.put(functionCallId, index));\n }\n }\n\n for (Event event : functionResponseEvents.subList(1, functionResponseEvents.size())) {\n if (!hasContentWithNonEmptyParts(event)) {\n continue;\n }\n\n for (Part part : event.content().get().parts().get()) {\n if (part.functionResponse().isPresent()) {\n Optional functionCallIdOpt = part.functionResponse().get().id();\n if (functionCallIdOpt.isPresent()) {\n String functionCallId = functionCallIdOpt.get();\n if (partIndicesInMergedEvent.containsKey(functionCallId)) {\n partsInMergedEvent.set(partIndicesInMergedEvent.get(functionCallId), part);\n } else {\n partsInMergedEvent.add(part);\n partIndicesInMergedEvent.put(functionCallId, partsInMergedEvent.size() - 1);\n }\n } else {\n partsInMergedEvent.add(part);\n }\n } else {\n partsInMergedEvent.add(part);\n }\n }\n }\n\n return baseEvent.toBuilder()\n .content(\n Optional.of(\n Content.builder().role(baseContent.role().get()).parts(partsInMergedEvent).build()))\n .build();\n }\n\n private static boolean hasContentWithNonEmptyParts(Event event) {\n return event\n .content() // Optional\n .flatMap(Content::parts) // Optional>\n .map(list -> !list.isEmpty()) // Optional\n .orElse(false);\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/retrieval/VertexAiRagRetrieval.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools.retrieval;\n\nimport static com.google.common.collect.ImmutableList.toImmutableList;\n\nimport com.google.adk.models.LlmRequest;\nimport com.google.adk.tools.ToolContext;\nimport com.google.cloud.aiplatform.v1.RagContexts;\nimport com.google.cloud.aiplatform.v1.RagQuery;\nimport com.google.cloud.aiplatform.v1.RetrieveContextsRequest;\nimport com.google.cloud.aiplatform.v1.RetrieveContextsRequest.VertexRagStore.RagResource;\nimport com.google.cloud.aiplatform.v1.RetrieveContextsResponse;\nimport com.google.cloud.aiplatform.v1.VertexRagServiceClient;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport com.google.genai.types.GenerateContentConfig;\nimport com.google.genai.types.Retrieval;\nimport com.google.genai.types.Tool;\nimport com.google.genai.types.VertexRagStore;\nimport com.google.genai.types.VertexRagStoreRagResource;\nimport io.reactivex.rxjava3.core.Completable;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.List;\nimport java.util.Map;\nimport javax.annotation.Nonnull;\nimport javax.annotation.Nullable;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * A retrieval tool that fetches context from Vertex AI RAG.\n *\n *

This tool allows to retrieve relevant information based on a query using Vertex AI RAG\n * service. It supports configuration of rag resources and a vector distance threshold.\n */\npublic class VertexAiRagRetrieval extends BaseRetrievalTool {\n private static final Logger logger = LoggerFactory.getLogger(VertexAiRagRetrieval.class);\n private final VertexRagServiceClient vertexRagServiceClient;\n private final String parent;\n private final List ragResources;\n private final Double vectorDistanceThreshold;\n private final VertexRagStore vertexRagStore;\n private final RetrieveContextsRequest.VertexRagStore apiVertexRagStore;\n\n public VertexAiRagRetrieval(\n @Nonnull String name,\n @Nonnull String description,\n @Nonnull VertexRagServiceClient vertexRagServiceClient,\n @Nonnull String parent,\n @Nullable List ragResources,\n @Nullable Double vectorDistanceThreshold) {\n super(name, description);\n this.vertexRagServiceClient = vertexRagServiceClient;\n this.parent = parent;\n this.ragResources = ragResources;\n this.vectorDistanceThreshold = vectorDistanceThreshold;\n\n // For Gemini 2\n VertexRagStore.Builder vertexRagStoreBuilder = VertexRagStore.builder();\n if (this.ragResources != null) {\n vertexRagStoreBuilder.ragResources(\n this.ragResources.stream()\n .map(\n ragResource ->\n VertexRagStoreRagResource.builder()\n .ragCorpus(ragResource.getRagCorpus())\n .build())\n .collect(toImmutableList()));\n }\n if (this.vectorDistanceThreshold != null) {\n vertexRagStoreBuilder.vectorDistanceThreshold(this.vectorDistanceThreshold);\n }\n this.vertexRagStore = vertexRagStoreBuilder.build();\n\n // For runAsync\n RetrieveContextsRequest.VertexRagStore.Builder apiVertexRagStoreBuilder =\n RetrieveContextsRequest.VertexRagStore.newBuilder();\n if (this.ragResources != null) {\n apiVertexRagStoreBuilder.addAllRagResources(this.ragResources);\n }\n if (this.vectorDistanceThreshold != null) {\n apiVertexRagStoreBuilder.setVectorDistanceThreshold(this.vectorDistanceThreshold);\n }\n this.apiVertexRagStore = apiVertexRagStoreBuilder.build();\n }\n\n @Override\n @CanIgnoreReturnValue\n public Completable processLlmRequest(\n LlmRequest.Builder llmRequestBuilder, ToolContext toolContext) {\n LlmRequest llmRequest = llmRequestBuilder.build();\n // Use Gemini built-in Vertex AI RAG tool for Gemini 2 models or when using Vertex AI API Model\n boolean useVertexAi = Boolean.parseBoolean(System.getenv(\"GOOGLE_GENAI_USE_VERTEXAI\"));\n if (useVertexAi\n && (llmRequest.model().isPresent() && llmRequest.model().get().startsWith(\"gemini-2\"))) {\n GenerateContentConfig config =\n llmRequest.config().orElse(GenerateContentConfig.builder().build());\n ImmutableList.Builder toolsBuilder = ImmutableList.builder();\n if (config.tools().isPresent()) {\n toolsBuilder.addAll(config.tools().get());\n }\n toolsBuilder.add(\n Tool.builder()\n .retrieval(Retrieval.builder().vertexRagStore(this.vertexRagStore).build())\n .build());\n logger.info(\n \"Using Gemini built-in Vertex AI RAG tool for model: {}\", llmRequest.model().get());\n llmRequestBuilder.config(config.toBuilder().tools(toolsBuilder.build()).build());\n return Completable.complete();\n } else {\n // Add the function declaration to the tools\n return super.processLlmRequest(llmRequestBuilder, toolContext);\n }\n }\n\n @Override\n public Single> runAsync(Map args, ToolContext toolContext) {\n String query = (String) args.get(\"query\");\n logger.info(\"VertexAiRagRetrieval.runAsync called with query: {}\", query);\n return Single.fromCallable(\n () -> {\n logger.info(\"Retrieving context for query: {}\", query);\n RetrieveContextsRequest retrieveContextsRequest =\n RetrieveContextsRequest.newBuilder()\n .setParent(this.parent)\n .setQuery(RagQuery.newBuilder().setText(query))\n .setVertexRagStore(this.apiVertexRagStore)\n .build();\n logger.info(\"Request to VertexRagService: {}\", retrieveContextsRequest);\n RetrieveContextsResponse response =\n this.vertexRagServiceClient.retrieveContexts(retrieveContextsRequest);\n logger.info(\"Response from VertexRagService: {}\", response);\n if (response.getContexts().getContextsList().isEmpty()) {\n logger.warn(\"No matching result found for query: {}\", query);\n return ImmutableMap.of(\n \"response\",\n String.format(\n \"No matching result found with the config: resources: %s\", this.ragResources));\n } else {\n logger.info(\n \"Found {} matching results for query: {}\",\n response.getContexts().getContextsCount(),\n query);\n ImmutableList contexts =\n response.getContexts().getContextsList().stream()\n .map(RagContexts.Context::getText)\n .collect(toImmutableList());\n logger.info(\"Returning contexts: {}\", contexts);\n return ImmutableMap.of(\"response\", contexts);\n }\n });\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/models/LlmRequest.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.models;\n\nimport static com.google.common.collect.ImmutableList.toImmutableList;\nimport static com.google.common.collect.ImmutableMap.toImmutableMap;\n\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonIgnore;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.databind.annotation.JsonDeserialize;\nimport com.google.adk.JsonBaseModel;\nimport com.google.adk.tools.BaseTool;\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.GenerateContentConfig;\nimport com.google.genai.types.LiveConnectConfig;\nimport com.google.genai.types.Part;\nimport com.google.genai.types.Schema;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.stream.Stream;\n\n/** Represents a request to be sent to the LLM. */\n@AutoValue\n@JsonDeserialize(builder = LlmRequest.Builder.class)\npublic abstract class LlmRequest extends JsonBaseModel {\n\n /**\n * Returns the name of the LLM model to be used. If not set, the default model of the LLM class\n * will be used.\n *\n * @return An optional string representing the model name.\n */\n @JsonProperty(\"model\")\n public abstract Optional model();\n\n /**\n * Returns the list of content sent to the LLM.\n *\n * @return A list of {@link Content} objects.\n */\n @JsonProperty(\"contents\")\n public abstract List contents();\n\n /**\n * Returns the configuration for content generation.\n *\n * @return An optional {@link GenerateContentConfig} object containing the generation settings.\n */\n @JsonProperty(\"config\")\n public abstract Optional config();\n\n /**\n * Returns the configuration for live connections. Populated using the RunConfig in the\n * InvocationContext.\n *\n * @return An optional {@link LiveConnectConfig} object containing the live connection settings.\n */\n @JsonProperty(\"liveConnectConfig\")\n public abstract LiveConnectConfig liveConnectConfig();\n\n /**\n * Returns a map of tools available to the LLM.\n *\n * @return A map where keys are tool names and values are {@link BaseTool} instances.\n */\n @JsonIgnore\n public abstract Map tools();\n\n /** returns the first system instruction text from the request if present. */\n @JsonIgnore\n public Optional getFirstSystemInstruction() {\n return this.config()\n .flatMap(GenerateContentConfig::systemInstruction)\n .flatMap(content -> content.parts().flatMap(partList -> partList.stream().findFirst()))\n .flatMap(Part::text);\n }\n\n /** Returns all system instruction texts from the request as an immutable list. */\n @JsonIgnore\n public ImmutableList getSystemInstructions() {\n return config()\n .flatMap(GenerateContentConfig::systemInstruction)\n .flatMap(Content::parts)\n .map(\n partList ->\n partList.stream()\n .map(Part::text)\n .flatMap(Optional::stream)\n .collect(toImmutableList()))\n .orElse(ImmutableList.of());\n }\n\n public static Builder builder() {\n return new AutoValue_LlmRequest.Builder()\n .tools(ImmutableMap.of())\n .contents(ImmutableList.of())\n .liveConnectConfig(LiveConnectConfig.builder().build());\n }\n\n public abstract Builder toBuilder();\n\n /** Builder for constructing {@link LlmRequest} instances. */\n @AutoValue.Builder\n public abstract static class Builder {\n\n @JsonCreator\n private static Builder create() {\n return builder();\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"model\")\n public abstract Builder model(String model);\n\n @CanIgnoreReturnValue\n @JsonProperty(\"contents\")\n public abstract Builder contents(List contents);\n\n @CanIgnoreReturnValue\n @JsonProperty(\"config\")\n public abstract Builder config(GenerateContentConfig config);\n\n public abstract Optional config();\n\n @CanIgnoreReturnValue\n @JsonProperty(\"liveConnectConfig\")\n public abstract Builder liveConnectConfig(LiveConnectConfig liveConnectConfig);\n\n abstract LiveConnectConfig liveConnectConfig();\n\n @CanIgnoreReturnValue\n abstract Builder tools(Map tools);\n\n abstract Map tools();\n\n @CanIgnoreReturnValue\n public final Builder appendInstructions(List instructions) {\n if (instructions.isEmpty()) {\n return this;\n }\n GenerateContentConfig config = config().orElse(GenerateContentConfig.builder().build());\n ImmutableList.Builder parts = ImmutableList.builder();\n if (config.systemInstruction().isPresent()) {\n parts.addAll(config.systemInstruction().get().parts().orElse(ImmutableList.of()));\n }\n parts.addAll(\n instructions.stream()\n .map(instruction -> Part.builder().text(instruction).build())\n .collect(toImmutableList()));\n config(\n config.toBuilder()\n .systemInstruction(\n Content.builder()\n .parts(parts.build())\n .role(\n config\n .systemInstruction()\n .map(c -> c.role().orElse(\"user\"))\n .orElse(\"user\"))\n .build())\n .build());\n\n LiveConnectConfig liveConfig = liveConnectConfig();\n ImmutableList.Builder livePartsBuilder = ImmutableList.builder();\n\n if (liveConfig.systemInstruction().isPresent()) {\n livePartsBuilder.addAll(\n liveConfig.systemInstruction().get().parts().orElse(ImmutableList.of()));\n }\n\n livePartsBuilder.addAll(\n instructions.stream()\n .map(instruction -> Part.builder().text(instruction).build())\n .collect(toImmutableList()));\n\n return liveConnectConfig(\n liveConfig.toBuilder()\n .systemInstruction(\n Content.builder()\n .parts(livePartsBuilder.build())\n .role(\n liveConfig\n .systemInstruction()\n .map(c -> c.role().orElse(\"user\"))\n .orElse(\"user\"))\n .build())\n .build());\n }\n\n @CanIgnoreReturnValue\n public final Builder appendTools(List tools) {\n if (tools.isEmpty()) {\n return this;\n }\n return tools(\n ImmutableMap.builder()\n .putAll(\n Stream.concat(tools.stream(), tools().values().stream())\n .collect(\n toImmutableMap(\n BaseTool::name,\n tool -> tool,\n (tool1, tool2) -> {\n throw new IllegalArgumentException(\n String.format(\"Duplicate tool name: %s\", tool1.name()));\n })))\n .buildOrThrow());\n }\n\n /**\n * Sets the output schema for the LLM response. If set, The output content will always be a JSON\n * string that conforms to the schema.\n */\n @CanIgnoreReturnValue\n public final Builder outputSchema(Schema schema) {\n GenerateContentConfig config = config().orElse(GenerateContentConfig.builder().build());\n return config(\n config.toBuilder().responseSchema(schema).responseMimeType(\"application/json\").build());\n }\n\n public abstract LlmRequest build();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/sessions/VertexAiSessionService.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\nimport static com.google.common.base.Strings.nullToEmpty;\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static java.util.stream.Collectors.toCollection;\n\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.google.adk.JsonBaseModel;\nimport com.google.adk.events.Event;\nimport com.google.adk.events.EventActions;\nimport com.google.auth.oauth2.GoogleCredentials;\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.FinishReason;\nimport com.google.genai.types.GroundingMetadata;\nimport com.google.genai.types.HttpOptions;\nimport com.google.genai.types.Part;\nimport io.reactivex.rxjava3.core.Completable;\nimport io.reactivex.rxjava3.core.Maybe;\nimport io.reactivex.rxjava3.core.Single;\nimport java.io.IOException;\nimport java.io.UncheckedIOException;\nimport java.time.Instant;\nimport java.util.ArrayList;\nimport java.util.Comparator;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentMap;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport javax.annotation.Nullable;\nimport okhttp3.ResponseBody;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/** Connects to the managed Vertex AI Session Service. */\n/** TODO: Use the genai HttpApiClient and ApiResponse methods once they are public. */\npublic final class VertexAiSessionService implements BaseSessionService {\n private static final int MAX_RETRY_ATTEMPTS = 5;\n private static final ObjectMapper objectMapper = JsonBaseModel.getMapper();\n private static final Logger logger = LoggerFactory.getLogger(VertexAiSessionService.class);\n\n private final HttpApiClient apiClient;\n\n /**\n * Creates a new instance of the Vertex AI Session Service with a custom ApiClient for testing.\n */\n public VertexAiSessionService(String project, String location, HttpApiClient apiClient) {\n this.apiClient = apiClient;\n }\n\n /** Creates a session service with default configuration. */\n public VertexAiSessionService() {\n this.apiClient =\n new HttpApiClient(Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty());\n }\n\n /** Creates a session service with specified project, location, credentials, and HTTP options. */\n public VertexAiSessionService(\n String project,\n String location,\n Optional credentials,\n Optional httpOptions) {\n this.apiClient =\n new HttpApiClient(Optional.of(project), Optional.of(location), credentials, httpOptions);\n }\n\n /**\n * Parses the JSON response body from the given API response.\n *\n * @throws UncheckedIOException if parsing fails.\n */\n private static JsonNode getJsonResponse(ApiResponse apiResponse) {\n try {\n ResponseBody responseBody = apiResponse.getResponseBody();\n return objectMapper.readTree(responseBody.string());\n } catch (IOException e) {\n throw new UncheckedIOException(e);\n }\n }\n\n @Override\n public Single createSession(\n String appName,\n String userId,\n @Nullable ConcurrentMap state,\n @Nullable String sessionId) {\n\n String reasoningEngineId = parseReasoningEngineId(appName);\n ConcurrentHashMap sessionJsonMap = new ConcurrentHashMap<>();\n sessionJsonMap.put(\"userId\", userId);\n if (state != null) {\n sessionJsonMap.put(\"sessionState\", state);\n }\n\n ApiResponse apiResponse;\n try {\n apiResponse =\n apiClient.request(\n \"POST\",\n \"reasoningEngines/\" + reasoningEngineId + \"/sessions\",\n objectMapper.writeValueAsString(sessionJsonMap));\n } catch (IOException e) {\n throw new UncheckedIOException(e);\n }\n\n logger.debug(\"Create Session response {}\", apiResponse.getResponseBody());\n String sessionName = \"\";\n String operationId = \"\";\n String sessId = nullToEmpty(sessionId);\n if (apiResponse.getResponseBody() != null) {\n JsonNode jsonResponse = getJsonResponse(apiResponse);\n sessionName = jsonResponse.get(\"name\").asText();\n List parts = Splitter.on('/').splitToList(sessionName);\n sessId = parts.get(parts.size() - 3);\n operationId = Iterables.getLast(parts);\n }\n for (int i = 0; i < MAX_RETRY_ATTEMPTS; i++) {\n ApiResponse lroResponse = apiClient.request(\"GET\", \"operations/\" + operationId, \"\");\n JsonNode jsonResponse = getJsonResponse(lroResponse);\n if (jsonResponse.get(\"done\") != null) {\n break;\n }\n try {\n SECONDS.sleep(1);\n } catch (InterruptedException e) {\n logger.warn(\"Error during sleep\", e);\n }\n }\n\n ApiResponse getSessionApiResponse =\n apiClient.request(\n \"GET\", \"reasoningEngines/\" + reasoningEngineId + \"/sessions/\" + sessId, \"\");\n JsonNode getSessionResponseMap = getJsonResponse(getSessionApiResponse);\n Instant updateTimestamp = Instant.parse(getSessionResponseMap.get(\"updateTime\").asText());\n ConcurrentMap sessionState = null;\n if (getSessionResponseMap != null && getSessionResponseMap.has(\"sessionState\")) {\n JsonNode sessionStateNode = getSessionResponseMap.get(\"sessionState\");\n if (sessionStateNode != null) {\n sessionState =\n objectMapper.convertValue(\n sessionStateNode, new TypeReference>() {});\n }\n }\n return Single.just(\n Session.builder(sessId)\n .appName(appName)\n .userId(userId)\n .lastUpdateTime(updateTimestamp)\n .state(sessionState == null ? new ConcurrentHashMap<>() : sessionState)\n .build());\n }\n\n @Override\n public Single listSessions(String appName, String userId) {\n String reasoningEngineId = parseReasoningEngineId(appName);\n\n ApiResponse apiResponse =\n apiClient.request(\n \"GET\",\n \"reasoningEngines/\" + reasoningEngineId + \"/sessions?filter=user_id=\" + userId,\n \"\");\n\n // Handles empty response case\n if (apiResponse.getResponseBody() == null) {\n return Single.just(ListSessionsResponse.builder().build());\n }\n\n JsonNode listSessionsResponseMap = getJsonResponse(apiResponse);\n List> apiSessions =\n objectMapper.convertValue(\n listSessionsResponseMap.get(\"sessions\"),\n new TypeReference>>() {});\n\n List sessions = new ArrayList<>();\n for (Map apiSession : apiSessions) {\n String sessionId =\n Iterables.getLast(Splitter.on('/').splitToList((String) apiSession.get(\"name\")));\n Instant updateTimestamp = Instant.parse((String) apiSession.get(\"updateTime\"));\n Session session =\n Session.builder(sessionId)\n .appName(appName)\n .userId(userId)\n .state(new ConcurrentHashMap<>())\n .lastUpdateTime(updateTimestamp)\n .build();\n sessions.add(session);\n }\n return Single.just(ListSessionsResponse.builder().sessions(sessions).build());\n }\n\n @Override\n public Single listEvents(String appName, String userId, String sessionId) {\n String reasoningEngineId = parseReasoningEngineId(appName);\n ApiResponse apiResponse =\n apiClient.request(\n \"GET\",\n \"reasoningEngines/\" + reasoningEngineId + \"/sessions/\" + sessionId + \"/events\",\n \"\");\n\n logger.debug(\"List events response {}\", apiResponse);\n\n if (apiResponse.getResponseBody() == null) {\n return Single.just(ListEventsResponse.builder().build());\n }\n\n JsonNode sessionEventsNode = getJsonResponse(apiResponse).get(\"sessionEvents\");\n if (sessionEventsNode == null || sessionEventsNode.isEmpty()) {\n return Single.just(ListEventsResponse.builder().events(new ArrayList<>()).build());\n }\n return Single.just(\n ListEventsResponse.builder()\n .events(\n objectMapper\n .convertValue(\n sessionEventsNode,\n new TypeReference>>() {})\n .stream()\n .map(event -> fromApiEvent(event))\n .collect(toCollection(ArrayList::new)))\n .build());\n }\n\n @Override\n public Maybe getSession(\n String appName, String userId, String sessionId, Optional config) {\n String reasoningEngineId = parseReasoningEngineId(appName);\n ApiResponse apiResponse =\n apiClient.request(\n \"GET\", \"reasoningEngines/\" + reasoningEngineId + \"/sessions/\" + sessionId, \"\");\n JsonNode getSessionResponseMap = getJsonResponse(apiResponse);\n\n if (getSessionResponseMap == null) {\n return Maybe.empty();\n }\n\n String sessId =\n Optional.ofNullable(getSessionResponseMap.get(\"name\"))\n .map(name -> Iterables.getLast(Splitter.on('/').splitToList(name.asText())))\n .orElse(sessionId);\n Instant updateTimestamp =\n Optional.ofNullable(getSessionResponseMap.get(\"updateTime\"))\n .map(updateTime -> Instant.parse(updateTime.asText()))\n .orElse(null);\n\n ConcurrentMap sessionState = new ConcurrentHashMap<>();\n if (getSessionResponseMap != null && getSessionResponseMap.has(\"sessionState\")) {\n sessionState.putAll(\n objectMapper.convertValue(\n getSessionResponseMap.get(\"sessionState\"),\n new TypeReference>() {}));\n }\n\n return listEvents(appName, userId, sessionId)\n .map(\n response -> {\n Session.Builder sessionBuilder =\n Session.builder(sessId)\n .appName(appName)\n .userId(userId)\n .lastUpdateTime(updateTimestamp)\n .state(sessionState);\n List events = response.events();\n if (events.isEmpty()) {\n return sessionBuilder.build();\n }\n events =\n events.stream()\n .filter(\n event ->\n updateTimestamp == null\n || Instant.ofEpochMilli(event.timestamp())\n .isBefore(updateTimestamp))\n .sorted(Comparator.comparing(Event::timestamp))\n .collect(toCollection(ArrayList::new));\n\n if (config.isPresent()) {\n if (config.get().numRecentEvents().isPresent()) {\n int numRecentEvents = config.get().numRecentEvents().get();\n if (events.size() > numRecentEvents) {\n events = events.subList(events.size() - numRecentEvents, events.size());\n }\n } else if (config.get().afterTimestamp().isPresent()) {\n Instant afterTimestamp = config.get().afterTimestamp().get();\n int i = events.size() - 1;\n while (i >= 0) {\n if (Instant.ofEpochMilli(events.get(i).timestamp()).isBefore(afterTimestamp)) {\n break;\n }\n i -= 1;\n }\n if (i >= 0) {\n events = events.subList(i, events.size());\n }\n }\n }\n return sessionBuilder.events(events).build();\n })\n .toMaybe();\n }\n\n @Override\n public Completable deleteSession(String appName, String userId, String sessionId) {\n String reasoningEngineId = parseReasoningEngineId(appName);\n ApiResponse unused =\n apiClient.request(\n \"DELETE\", \"reasoningEngines/\" + reasoningEngineId + \"/sessions/\" + sessionId, \"\");\n return Completable.complete();\n }\n\n @Override\n public Single appendEvent(Session session, Event event) {\n BaseSessionService.super.appendEvent(session, event);\n\n String reasoningEngineId = parseReasoningEngineId(session.appName());\n ApiResponse response =\n apiClient.request(\n \"POST\",\n \"reasoningEngines/\" + reasoningEngineId + \"/sessions/\" + session.id() + \":appendEvent\",\n convertEventToJson(event));\n // TODO(b/414263934)): Improve error handling for appendEvent.\n try {\n if (response.getResponseBody().string().contains(\"com.google.genai.errors.ClientException\")) {\n logger.warn(\"Failed to append event: \", event);\n }\n } catch (IOException e) {\n throw new UncheckedIOException(e);\n }\n\n response.close();\n return Single.just(event);\n }\n\n /**\n * Converts an {@link Event} to its JSON string representation for API transmission.\n *\n * @return JSON string of the event.\n * @throws UncheckedIOException if serialization fails.\n */\n static String convertEventToJson(Event event) {\n Map metadataJson = new HashMap<>();\n metadataJson.put(\"partial\", event.partial());\n metadataJson.put(\"turnComplete\", event.turnComplete());\n metadataJson.put(\"interrupted\", event.interrupted());\n metadataJson.put(\"branch\", event.branch().orElse(null));\n metadataJson.put(\n \"long_running_tool_ids\",\n event.longRunningToolIds() != null ? event.longRunningToolIds().orElse(null) : null);\n if (event.groundingMetadata() != null) {\n metadataJson.put(\"grounding_metadata\", event.groundingMetadata());\n }\n\n Map eventJson = new HashMap<>();\n eventJson.put(\"author\", event.author());\n eventJson.put(\"invocationId\", event.invocationId());\n eventJson.put(\n \"timestamp\",\n new HashMap<>(\n ImmutableMap.of(\n \"seconds\",\n event.timestamp() / 1000,\n \"nanos\",\n (event.timestamp() % 1000) * 1000000)));\n if (event.errorCode().isPresent()) {\n eventJson.put(\"errorCode\", event.errorCode());\n }\n if (event.errorMessage().isPresent()) {\n eventJson.put(\"errorMessage\", event.errorMessage());\n }\n eventJson.put(\"eventMetadata\", metadataJson);\n\n if (event.actions() != null) {\n Map actionsJson = new HashMap<>();\n actionsJson.put(\"skipSummarization\", event.actions().skipSummarization());\n actionsJson.put(\"stateDelta\", event.actions().stateDelta());\n actionsJson.put(\"artifactDelta\", event.actions().artifactDelta());\n actionsJson.put(\"transferAgent\", event.actions().transferToAgent());\n actionsJson.put(\"escalate\", event.actions().escalate());\n actionsJson.put(\"requestedAuthConfigs\", event.actions().requestedAuthConfigs());\n eventJson.put(\"actions\", actionsJson);\n }\n if (event.content().isPresent()) {\n eventJson.put(\"content\", SessionUtils.encodeContent(event.content().get()));\n }\n if (event.errorCode().isPresent()) {\n eventJson.put(\"errorCode\", event.errorCode().get());\n }\n if (event.errorMessage().isPresent()) {\n eventJson.put(\"errorMessage\", event.errorMessage().get());\n }\n try {\n return objectMapper.writeValueAsString(eventJson);\n } catch (JsonProcessingException e) {\n throw new UncheckedIOException(e);\n }\n }\n\n /**\n * Converts a raw value to a {@link Content} object.\n *\n * @return parsed {@link Content}, or {@code null} if conversion fails.\n */\n @Nullable\n @SuppressWarnings(\"unchecked\")\n private static Content convertMapToContent(Object rawContentValue) {\n if (rawContentValue == null) {\n return null;\n }\n\n if (rawContentValue instanceof Map) {\n Map contentMap = (Map) rawContentValue;\n try {\n return objectMapper.convertValue(contentMap, Content.class);\n } catch (IllegalArgumentException e) {\n logger.warn(\"Error converting Map to Content\", e);\n return null;\n }\n } else {\n logger.warn(\n \"Unexpected type for 'content' in apiEvent: {}\", rawContentValue.getClass().getName());\n return null;\n }\n }\n\n /**\n * Extracts the reasoning engine ID from the given app name or full resource name.\n *\n * @return reasoning engine ID.\n * @throws IllegalArgumentException if format is invalid.\n */\n static String parseReasoningEngineId(String appName) {\n if (appName.matches(\"\\\\d+\")) {\n return appName;\n }\n\n Matcher matcher = APP_NAME_PATTERN.matcher(appName);\n\n if (!matcher.matches()) {\n throw new IllegalArgumentException(\n \"App name \"\n + appName\n + \" is not valid. It should either be the full\"\n + \" ReasoningEngine resource name, or the reasoning engine id.\");\n }\n\n return matcher.group(matcher.groupCount());\n }\n\n /**\n * Converts raw API event data into an {@link Event} object.\n *\n * @return parsed {@link Event}.\n */\n @SuppressWarnings(\"unchecked\")\n static Event fromApiEvent(Map apiEvent) {\n EventActions eventActions = new EventActions();\n if (apiEvent.get(\"actions\") != null) {\n Map actionsMap = (Map) apiEvent.get(\"actions\");\n eventActions.setSkipSummarization(\n Optional.ofNullable(actionsMap.get(\"skipSummarization\")).map(value -> (Boolean) value));\n eventActions.setStateDelta(\n actionsMap.get(\"stateDelta\") != null\n ? new ConcurrentHashMap<>((Map) actionsMap.get(\"stateDelta\"))\n : new ConcurrentHashMap<>());\n eventActions.setArtifactDelta(\n actionsMap.get(\"artifactDelta\") != null\n ? new ConcurrentHashMap<>((Map) actionsMap.get(\"artifactDelta\"))\n : new ConcurrentHashMap<>());\n eventActions.setTransferToAgent(\n actionsMap.get(\"transferAgent\") != null\n ? (String) actionsMap.get(\"transferAgent\")\n : null);\n eventActions.setEscalate(\n Optional.ofNullable(actionsMap.get(\"escalate\")).map(value -> (Boolean) value));\n eventActions.setRequestedAuthConfigs(\n Optional.ofNullable(actionsMap.get(\"requestedAuthConfigs\"))\n .map(VertexAiSessionService::asConcurrentMapOfConcurrentMaps)\n .orElse(new ConcurrentHashMap<>()));\n }\n\n Event event =\n Event.builder()\n .id((String) Iterables.getLast(Splitter.on('/').split(apiEvent.get(\"name\").toString())))\n .invocationId((String) apiEvent.get(\"invocationId\"))\n .author((String) apiEvent.get(\"author\"))\n .actions(eventActions)\n .content(\n Optional.ofNullable(apiEvent.get(\"content\"))\n .map(VertexAiSessionService::convertMapToContent)\n .map(SessionUtils::decodeContent)\n .orElse(null))\n .timestamp(convertToInstant(apiEvent.get(\"timestamp\")).toEpochMilli())\n .errorCode(\n Optional.ofNullable(apiEvent.get(\"errorCode\"))\n .map(value -> new FinishReason((String) value)))\n .errorMessage(\n Optional.ofNullable(apiEvent.get(\"errorMessage\")).map(value -> (String) value))\n .branch(Optional.ofNullable(apiEvent.get(\"branch\")).map(value -> (String) value))\n .build();\n // TODO(b/414263934): Add Event branch and grounding metadata for python parity.\n if (apiEvent.get(\"eventMetadata\") != null) {\n Map eventMetadata = (Map) apiEvent.get(\"eventMetadata\");\n List longRunningToolIdsList = (List) eventMetadata.get(\"longRunningToolIds\");\n\n GroundingMetadata groundingMetadata = null;\n Object rawGroundingMetadata = eventMetadata.get(\"groundingMetadata\");\n if (rawGroundingMetadata != null) {\n groundingMetadata =\n objectMapper.convertValue(rawGroundingMetadata, GroundingMetadata.class);\n }\n\n event =\n event.toBuilder()\n .partial(Optional.ofNullable((Boolean) eventMetadata.get(\"partial\")).orElse(false))\n .turnComplete(\n Optional.ofNullable((Boolean) eventMetadata.get(\"turnComplete\")).orElse(false))\n .interrupted(\n Optional.ofNullable((Boolean) eventMetadata.get(\"interrupted\")).orElse(false))\n .branch(Optional.ofNullable((String) eventMetadata.get(\"branch\")))\n .groundingMetadata(groundingMetadata)\n .longRunningToolIds(\n longRunningToolIdsList != null ? new HashSet<>(longRunningToolIdsList) : null)\n .build();\n }\n return event;\n }\n\n /**\n * Converts a timestamp from a Map or String into an {@link Instant}.\n *\n * @param timestampObj map with \"seconds\"/\"nanos\" or an ISO string.\n * @return parsed {@link Instant}.\n */\n private static Instant convertToInstant(Object timestampObj) {\n if (timestampObj instanceof Map timestampMap) {\n return Instant.ofEpochSecond(\n ((Number) timestampMap.get(\"seconds\")).longValue(),\n ((Number) timestampMap.get(\"nanos\")).longValue());\n } else if (timestampObj != null) {\n return Instant.parse(timestampObj.toString());\n } else {\n throw new IllegalArgumentException(\"Timestamp not found in apiEvent\");\n }\n }\n\n /**\n * Converts a nested map into a {@link ConcurrentMap} of {@link ConcurrentMap}s.\n *\n * @return thread-safe nested map.\n */\n @SuppressWarnings(\"unchecked\")\n private static ConcurrentMap>\n asConcurrentMapOfConcurrentMaps(Object value) {\n return ((Map>) value)\n .entrySet().stream()\n .collect(\n ConcurrentHashMap::new,\n (map, entry) -> map.put(entry.getKey(), new ConcurrentHashMap<>(entry.getValue())),\n ConcurrentHashMap::putAll);\n }\n\n /** Regex for parsing full ReasoningEngine resource names. */\n private static final Pattern APP_NAME_PATTERN =\n Pattern.compile(\n \"^projects/([a-zA-Z0-9-_]+)/locations/([a-zA-Z0-9-_]+)/reasoningEngines/(\\\\d+)$\");\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/Telemetry.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk;\n\nimport static com.google.common.collect.ImmutableList.toImmutableList;\n\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.events.Event;\nimport com.google.adk.models.LlmRequest;\nimport com.google.adk.models.LlmResponse;\nimport com.google.common.collect.ImmutableList;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.Part;\nimport io.opentelemetry.api.GlobalOpenTelemetry;\nimport io.opentelemetry.api.trace.Span;\nimport io.opentelemetry.api.trace.Tracer;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * Utility class for capturing and reporting telemetry data within the ADK. This class provides\n * methods to trace various aspects of the agent's execution, including tool calls, tool responses,\n * LLM interactions, and data handling. It leverages OpenTelemetry for tracing and logging for\n * detailed information. These traces can then be exported through the ADK Dev Server UI.\n */\npublic class Telemetry {\n\n private static final Logger log = LoggerFactory.getLogger(Telemetry.class);\n private static final Tracer tracer = GlobalOpenTelemetry.getTracer(\"gcp.vertex.agent\");\n\n private Telemetry() {}\n\n /**\n * Traces tool call arguments.\n *\n * @param args The arguments to the tool call.\n */\n public static void traceToolCall(Map args) {\n Span span = Span.current();\n if (span == null || !span.getSpanContext().isValid()) {\n log.trace(\"traceToolCall: No valid span in current context.\");\n return;\n }\n\n span.setAttribute(\"gen_ai.system\", \"gcp.vertex.agent\");\n try {\n span.setAttribute(\n \"gcp.vertex.agent.tool_call_args\", JsonBaseModel.getMapper().writeValueAsString(args));\n } catch (JsonProcessingException e) {\n log.warn(\"traceToolCall: Failed to serialize tool call args to JSON\", e);\n }\n }\n\n /**\n * Traces tool response event.\n *\n * @param invocationContext The invocation context for the current agent run.\n * @param eventId The ID of the event.\n * @param functionResponseEvent The function response event.\n */\n public static void traceToolResponse(\n InvocationContext invocationContext, String eventId, Event functionResponseEvent) {\n Span span = Span.current();\n if (span == null || !span.getSpanContext().isValid()) {\n log.trace(\"traceToolResponse: No valid span in current context.\");\n return;\n }\n\n span.setAttribute(\"gen_ai.system\", \"gcp.vertex.agent\");\n span.setAttribute(\"gcp.vertex.agent.invocation_id\", invocationContext.invocationId());\n span.setAttribute(\"gcp.vertex.agent.event_id\", eventId);\n span.setAttribute(\"gcp.vertex.agent.tool_response\", functionResponseEvent.toJson());\n\n // Setting empty llm request and response (as the AdkDevServer UI expects these)\n span.setAttribute(\"gcp.vertex.agent.llm_request\", \"{}\");\n span.setAttribute(\"gcp.vertex.agent.llm_response\", \"{}\");\n if (invocationContext.session() != null && invocationContext.session().id() != null) {\n span.setAttribute(\"gcp.vertex.agent.session_id\", invocationContext.session().id());\n }\n }\n\n /**\n * Builds a dictionary representation of the LLM request for tracing. {@code GenerationConfig} is\n * included as a whole. For other fields like {@code Content}, parts that cannot be easily\n * serialized or are not needed for the trace (e.g., inlineData) are excluded.\n *\n * @param llmRequest The LlmRequest object.\n * @return A Map representation of the LLM request for tracing.\n */\n private static Map buildLlmRequestForTrace(LlmRequest llmRequest) {\n Map result = new HashMap<>();\n result.put(\"model\", llmRequest.model().orElse(null));\n llmRequest.config().ifPresent(config -> result.put(\"config\", config));\n\n List contentsList = new ArrayList<>();\n for (Content content : llmRequest.contents()) {\n ImmutableList filteredParts =\n content.parts().orElse(ImmutableList.of()).stream()\n .filter(part -> part.inlineData().isEmpty())\n .collect(toImmutableList());\n\n Content.Builder contentBuilder = Content.builder();\n content.role().ifPresent(contentBuilder::role);\n contentBuilder.parts(filteredParts);\n contentsList.add(contentBuilder.build());\n }\n result.put(\"contents\", contentsList);\n return result;\n }\n\n /**\n * Traces a call to the LLM.\n *\n * @param invocationContext The invocation context.\n * @param eventId The ID of the event associated with this LLM call/response.\n * @param llmRequest The LLM request object.\n * @param llmResponse The LLM response object.\n */\n public static void traceCallLlm(\n InvocationContext invocationContext,\n String eventId,\n LlmRequest llmRequest,\n LlmResponse llmResponse) {\n Span span = Span.current();\n if (span == null || !span.getSpanContext().isValid()) {\n log.trace(\"traceCallLlm: No valid span in current context.\");\n return;\n }\n\n span.setAttribute(\"gen_ai.system\", \"gcp.vertex.agent\");\n llmRequest.model().ifPresent(modelName -> span.setAttribute(\"gen_ai.request.model\", modelName));\n span.setAttribute(\"gcp.vertex.agent.invocation_id\", invocationContext.invocationId());\n span.setAttribute(\"gcp.vertex.agent.event_id\", eventId);\n\n if (invocationContext.session() != null && invocationContext.session().id() != null) {\n span.setAttribute(\"gcp.vertex.agent.session_id\", invocationContext.session().id());\n } else {\n log.trace(\n \"traceCallLlm: InvocationContext session or session ID is null, cannot set\"\n + \" gcp.vertex.agent.session_id\");\n }\n\n try {\n span.setAttribute(\n \"gcp.vertex.agent.llm_request\",\n JsonBaseModel.getMapper().writeValueAsString(buildLlmRequestForTrace(llmRequest)));\n span.setAttribute(\"gcp.vertex.agent.llm_response\", llmResponse.toJson());\n } catch (JsonProcessingException e) {\n log.warn(\"traceCallLlm: Failed to serialize LlmRequest or LlmResponse to JSON\", e);\n }\n }\n\n /**\n * Traces the sending of data (history or new content) to the agent/model.\n *\n * @param invocationContext The invocation context.\n * @param eventId The ID of the event, if applicable.\n * @param data A list of content objects being sent.\n */\n public static void traceSendData(\n InvocationContext invocationContext, String eventId, List data) {\n Span span = Span.current();\n if (span == null || !span.getSpanContext().isValid()) {\n log.trace(\"traceSendData: No valid span in current context.\");\n return;\n }\n\n span.setAttribute(\"gcp.vertex.agent.invocation_id\", invocationContext.invocationId());\n if (eventId != null && !eventId.isEmpty()) {\n span.setAttribute(\"gcp.vertex.agent.event_id\", eventId);\n }\n\n if (invocationContext.session() != null && invocationContext.session().id() != null) {\n span.setAttribute(\"gcp.vertex.agent.session_id\", invocationContext.session().id());\n }\n\n try {\n List> dataList = new ArrayList<>();\n if (data != null) {\n for (Content content : data) {\n if (content != null) {\n dataList.add(\n JsonBaseModel.getMapper()\n .convertValue(content, new TypeReference>() {}));\n }\n }\n }\n span.setAttribute(\"gcp.vertex.agent.data\", JsonBaseModel.toJsonString(dataList));\n } catch (IllegalStateException e) {\n log.warn(\"traceSendData: Failed to serialize data to JSON\", e);\n }\n }\n\n /**\n * Gets the tracer.\n *\n * @return The tracer.\n */\n public static Tracer getTracer() {\n return tracer;\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/llmflows/Functions.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows.llmflows;\n\nimport com.google.adk.Telemetry;\nimport com.google.adk.agents.Callbacks.AfterToolCallback;\nimport com.google.adk.agents.Callbacks.BeforeToolCallback;\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.agents.LlmAgent;\nimport com.google.adk.events.Event;\nimport com.google.adk.events.EventActions;\nimport com.google.adk.tools.BaseTool;\nimport com.google.adk.tools.ToolContext;\nimport com.google.common.base.VerifyException;\nimport com.google.common.collect.ImmutableList;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.FunctionCall;\nimport com.google.genai.types.FunctionResponse;\nimport com.google.genai.types.Part;\nimport io.opentelemetry.api.trace.Span;\nimport io.opentelemetry.api.trace.Tracer;\nimport io.opentelemetry.context.Scope;\nimport io.reactivex.rxjava3.core.Flowable;\nimport io.reactivex.rxjava3.core.Maybe;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.Set;\nimport java.util.UUID;\nimport org.jspecify.annotations.Nullable;\n\n/** Utility class for handling function calls. */\npublic final class Functions {\n\n private static final String AF_FUNCTION_CALL_ID_PREFIX = \"adk-\";\n\n /** Generates a unique ID for a function call. */\n public static String generateClientFunctionCallId() {\n return AF_FUNCTION_CALL_ID_PREFIX + UUID.randomUUID();\n }\n\n /**\n * Populates missing function call IDs in the provided event's content.\n *\n *

If the event contains function calls without an ID, this method generates a unique\n * client-side ID for each and updates the event content.\n *\n * @param modelResponseEvent The event potentially containing function calls.\n */\n public static void populateClientFunctionCallId(Event modelResponseEvent) {\n Optional originalContentOptional = modelResponseEvent.content();\n if (originalContentOptional.isEmpty()) {\n return;\n }\n Content originalContent = originalContentOptional.get();\n List originalParts = originalContent.parts().orElse(ImmutableList.of());\n if (originalParts.stream().noneMatch(part -> part.functionCall().isPresent())) {\n return; // No function calls to process\n }\n\n List newParts = new ArrayList<>();\n boolean modified = false;\n for (Part part : originalParts) {\n if (part.functionCall().isPresent()) {\n FunctionCall functionCall = part.functionCall().get();\n if (functionCall.id().isEmpty() || functionCall.id().get().isEmpty()) {\n FunctionCall updatedFunctionCall =\n functionCall.toBuilder().id(generateClientFunctionCallId()).build();\n newParts.add(Part.builder().functionCall(updatedFunctionCall).build());\n modified = true;\n } else {\n newParts.add(part); // Keep original part if ID exists\n }\n } else {\n newParts.add(part); // Keep non-function call parts\n }\n }\n\n if (modified) {\n String role =\n originalContent\n .role()\n .orElseThrow(\n () ->\n new IllegalStateException(\n \"Content role is missing in event: \" + modelResponseEvent.id()));\n Content newContent = Content.builder().role(role).parts(newParts).build();\n modelResponseEvent.setContent(Optional.of(newContent));\n }\n }\n\n // TODO - b/413761119 add the remaining methods for function call id.\n\n public static Maybe handleFunctionCalls(\n InvocationContext invocationContext, Event functionCallEvent, Map tools) {\n ImmutableList functionCalls = functionCallEvent.functionCalls();\n\n List> functionResponseEvents = new ArrayList<>();\n\n for (FunctionCall functionCall : functionCalls) {\n if (!tools.containsKey(functionCall.name().get())) {\n throw new VerifyException(\"Tool not found: \" + functionCall.name().get());\n }\n BaseTool tool = tools.get(functionCall.name().get());\n ToolContext toolContext =\n ToolContext.builder(invocationContext)\n .functionCallId(functionCall.id().orElse(\"\"))\n .build();\n\n Map functionArgs = functionCall.args().orElse(new HashMap<>());\n\n Maybe> maybeFunctionResult =\n maybeInvokeBeforeToolCall(invocationContext, tool, functionArgs, toolContext)\n .switchIfEmpty(Maybe.defer(() -> callTool(tool, functionArgs, toolContext)));\n\n Maybe maybeFunctionResponseEvent =\n maybeFunctionResult\n .map(Optional::of)\n .defaultIfEmpty(Optional.empty())\n .flatMapMaybe(\n optionalInitialResult -> {\n Map initialFunctionResult = optionalInitialResult.orElse(null);\n\n Maybe> afterToolResultMaybe =\n maybeInvokeAfterToolCall(\n invocationContext,\n tool,\n functionArgs,\n toolContext,\n initialFunctionResult);\n\n return afterToolResultMaybe\n .map(Optional::of)\n .defaultIfEmpty(Optional.ofNullable(initialFunctionResult))\n .flatMapMaybe(\n finalOptionalResult -> {\n Map finalFunctionResult =\n finalOptionalResult.orElse(null);\n if (tool.longRunning() && finalFunctionResult == null) {\n return Maybe.empty();\n }\n Event functionResponseEvent =\n buildResponseEvent(\n tool, finalFunctionResult, toolContext, invocationContext);\n return Maybe.just(functionResponseEvent);\n });\n });\n\n functionResponseEvents.add(maybeFunctionResponseEvent);\n }\n\n return Maybe.merge(functionResponseEvents)\n .toList()\n .flatMapMaybe(\n events -> {\n if (events.isEmpty()) {\n return Maybe.empty();\n }\n Event mergedEvent = Functions.mergeParallelFunctionResponseEvents(events);\n if (mergedEvent == null) {\n return Maybe.empty();\n }\n\n if (events.size() > 1) {\n Tracer tracer = Telemetry.getTracer();\n Span mergedSpan = tracer.spanBuilder(\"tool_response\").startSpan();\n try (Scope scope = mergedSpan.makeCurrent()) {\n Telemetry.traceToolResponse(invocationContext, mergedEvent.id(), mergedEvent);\n } finally {\n mergedSpan.end();\n }\n }\n return Maybe.just(mergedEvent);\n });\n }\n\n public static Set getLongRunningFunctionCalls(\n List functionCalls, Map tools) {\n Set longRunningFunctionCalls = new HashSet<>();\n for (FunctionCall functionCall : functionCalls) {\n if (!tools.containsKey(functionCall.name().get())) {\n continue;\n }\n BaseTool tool = tools.get(functionCall.name().get());\n if (tool.longRunning()) {\n longRunningFunctionCalls.add(functionCall.id().orElse(\"\"));\n }\n }\n return longRunningFunctionCalls;\n }\n\n private static @Nullable Event mergeParallelFunctionResponseEvents(\n List functionResponseEvents) {\n if (functionResponseEvents.isEmpty()) {\n return null;\n }\n if (functionResponseEvents.size() == 1) {\n return functionResponseEvents.get(0);\n }\n // Use the first event as the base for common attributes\n Event baseEvent = functionResponseEvents.get(0);\n\n List mergedParts = new ArrayList<>();\n for (Event event : functionResponseEvents) {\n event.content().flatMap(Content::parts).ifPresent(mergedParts::addAll);\n }\n\n // Merge actions from all events\n // TODO: validate that pending actions are not cleared away\n EventActions.Builder mergedActionsBuilder = EventActions.builder();\n for (Event event : functionResponseEvents) {\n mergedActionsBuilder.merge(event.actions());\n }\n\n return Event.builder()\n .id(Event.generateEventId())\n .invocationId(baseEvent.invocationId())\n .author(baseEvent.author())\n .branch(baseEvent.branch())\n .content(Optional.of(Content.builder().role(\"user\").parts(mergedParts).build()))\n .actions(mergedActionsBuilder.build())\n .timestamp(baseEvent.timestamp())\n .build();\n }\n\n private static Maybe> maybeInvokeBeforeToolCall(\n InvocationContext invocationContext,\n BaseTool tool,\n Map functionArgs,\n ToolContext toolContext) {\n if (invocationContext.agent() instanceof LlmAgent) {\n LlmAgent agent = (LlmAgent) invocationContext.agent();\n\n Optional> callbacksOpt = agent.beforeToolCallback();\n if (callbacksOpt.isEmpty() || callbacksOpt.get().isEmpty()) {\n return Maybe.empty();\n }\n List callbacks = callbacksOpt.get();\n\n return Flowable.fromIterable(callbacks)\n .concatMapMaybe(\n callback -> callback.call(invocationContext, tool, functionArgs, toolContext))\n .firstElement();\n }\n return Maybe.empty();\n }\n\n private static Maybe> maybeInvokeAfterToolCall(\n InvocationContext invocationContext,\n BaseTool tool,\n Map functionArgs,\n ToolContext toolContext,\n Map functionResult) {\n if (invocationContext.agent() instanceof LlmAgent) {\n LlmAgent agent = (LlmAgent) invocationContext.agent();\n Optional> callbacksOpt = agent.afterToolCallback();\n if (callbacksOpt.isEmpty() || callbacksOpt.get().isEmpty()) {\n return Maybe.empty();\n }\n List callbacks = callbacksOpt.get();\n\n return Flowable.fromIterable(callbacks)\n .concatMapMaybe(\n callback ->\n callback.call(invocationContext, tool, functionArgs, toolContext, functionResult))\n .firstElement();\n }\n return Maybe.empty();\n }\n\n private static Maybe> callTool(\n BaseTool tool, Map args, ToolContext toolContext) {\n Tracer tracer = Telemetry.getTracer();\n return Maybe.defer(\n () -> {\n Span span = tracer.spanBuilder(\"tool_call [\" + tool.name() + \"]\").startSpan();\n try (Scope scope = span.makeCurrent()) {\n Telemetry.traceToolCall(args);\n return tool.runAsync(args, toolContext)\n .toMaybe()\n .doOnError(span::recordException)\n .doFinally(span::end);\n } catch (RuntimeException e) {\n span.recordException(e);\n span.end();\n return Maybe.error(new RuntimeException(\"Failed to call tool: \" + tool.name(), e));\n }\n });\n }\n\n private static Event buildResponseEvent(\n BaseTool tool,\n Map response,\n ToolContext toolContext,\n InvocationContext invocationContext) {\n Tracer tracer = Telemetry.getTracer();\n Span span = tracer.spanBuilder(\"tool_response [\" + tool.name() + \"]\").startSpan();\n try (Scope scope = span.makeCurrent()) {\n // use a empty placeholder response if tool response is null.\n if (response == null) {\n response = new HashMap<>();\n }\n\n Part partFunctionResponse =\n Part.builder()\n .functionResponse(\n FunctionResponse.builder()\n .id(toolContext.functionCallId().orElse(\"\"))\n .name(tool.name())\n .response(response)\n .build())\n .build();\n\n Event event =\n Event.builder()\n .id(Event.generateEventId())\n .invocationId(invocationContext.invocationId())\n .author(invocationContext.agent().name())\n .branch(invocationContext.branch())\n .content(\n Optional.of(\n Content.builder()\n .role(\"user\")\n .parts(Collections.singletonList(partFunctionResponse))\n .build()))\n .actions(toolContext.eventActions())\n .build();\n Telemetry.traceToolResponse(invocationContext, event.id(), event);\n return event;\n } finally {\n span.end();\n }\n }\n\n private Functions() {}\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/LoadArtifactsTool.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// LoadArtifactsTool.java\npackage com.google.adk.tools;\n\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.google.adk.JsonBaseModel;\nimport com.google.adk.models.LlmRequest;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.FunctionDeclaration;\nimport com.google.genai.types.FunctionResponse;\nimport com.google.genai.types.Part;\nimport com.google.genai.types.Schema;\nimport io.reactivex.rxjava3.core.Completable;\nimport io.reactivex.rxjava3.core.Observable;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.Optional;\n\n/**\n * A tool that loads artifacts and adds them to the session.\n *\n *

This tool informs the model about available artifacts and provides their content when\n * requested by the model through a function call.\n */\npublic final class LoadArtifactsTool extends BaseTool {\n public LoadArtifactsTool() {\n super(\"load_artifacts\", \"Loads the artifacts and adds them to the session.\");\n }\n\n @Override\n public Optional declaration() {\n return Optional.of(\n FunctionDeclaration.builder()\n .name(this.name())\n .description(this.description())\n .parameters(\n Schema.builder()\n .type(\"OBJECT\")\n .properties(\n ImmutableMap.of(\n \"artifact_names\",\n Schema.builder()\n .type(\"ARRAY\")\n .items(Schema.builder().type(\"STRING\").build())\n .build()))\n .build())\n .build());\n }\n\n @Override\n public Single> runAsync(Map args, ToolContext toolContext) {\n @SuppressWarnings(\"unchecked\")\n List artifactNames =\n (List) args.getOrDefault(\"artifact_names\", ImmutableList.of());\n return Single.just(ImmutableMap.of(\"artifact_names\", artifactNames));\n }\n\n @Override\n public Completable processLlmRequest(\n LlmRequest.Builder llmRequestBuilder, ToolContext toolContext) {\n return super.processLlmRequest(llmRequestBuilder, toolContext)\n .andThen(appendArtifactsToLlmRequest(llmRequestBuilder, toolContext));\n }\n\n public Completable appendArtifactsToLlmRequest(\n LlmRequest.Builder llmRequestBuilder, ToolContext toolContext) {\n\n return toolContext\n .listArtifacts()\n .flatMapCompletable(\n artifactNamesList -> {\n if (artifactNamesList.isEmpty()) {\n return Completable.complete();\n }\n\n appendInitialInstructions(llmRequestBuilder, artifactNamesList);\n\n return processLoadArtifactsFunctionCall(llmRequestBuilder, toolContext);\n });\n }\n\n private void appendInitialInstructions(\n LlmRequest.Builder llmRequestBuilder, List artifactNamesList) {\n try {\n String instructions =\n String.format(\n \"You have a list of artifacts:\\n %s\\n\\nWhen the user asks questions about\"\n + \" any of the artifacts, you should call the `load_artifacts` function\"\n + \" to load the artifact. Do not generate any text other than the\"\n + \" function call.\",\n JsonBaseModel.getMapper().writeValueAsString(artifactNamesList));\n llmRequestBuilder.appendInstructions(ImmutableList.of(instructions));\n } catch (JsonProcessingException e) {\n throw new IllegalStateException(\"Failed to serialize artifact names to JSON\", e);\n }\n }\n\n private Completable processLoadArtifactsFunctionCall(\n LlmRequest.Builder llmRequestBuilder, ToolContext toolContext) {\n\n LlmRequest currentRequestState = llmRequestBuilder.build();\n List currentContents = currentRequestState.contents();\n\n if (currentContents.isEmpty()) {\n return Completable.complete();\n }\n\n return Iterables.getLast(currentContents)\n .parts()\n .filter(partsList -> !partsList.isEmpty())\n .flatMap(partsList -> partsList.get(0).functionResponse())\n .filter(fr -> Objects.equals(fr.name().orElse(null), \"load_artifacts\"))\n .flatMap(FunctionResponse::response)\n .flatMap(responseMap -> Optional.ofNullable(responseMap.get(\"artifact_names\")))\n .filter(obj -> obj instanceof List)\n .map(obj -> (List) obj)\n .filter(list -> !list.isEmpty())\n .map(\n artifactNamesRaw -> {\n @SuppressWarnings(\"unchecked\")\n List artifactNamesToLoad = (List) artifactNamesRaw;\n\n return Observable.fromIterable(artifactNamesToLoad)\n .flatMapCompletable(\n artifactName ->\n loadAndAppendIndividualArtifact(\n llmRequestBuilder, toolContext, artifactName));\n })\n .orElse(Completable.complete());\n }\n\n private Completable loadAndAppendIndividualArtifact(\n LlmRequest.Builder llmRequestBuilder, ToolContext toolContext, String artifactName) {\n\n return toolContext\n .loadArtifact(artifactName, Optional.empty())\n .flatMapCompletable(\n actualArtifact ->\n Completable.fromAction(\n () ->\n appendArtifactToLlmRequest(\n llmRequestBuilder,\n \"Artifact \" + artifactName + \" is:\",\n actualArtifact)));\n }\n\n private void appendArtifactToLlmRequest(\n LlmRequest.Builder llmRequestBuilder, String prefix, Part artifact) {\n llmRequestBuilder.contents(\n ImmutableList.builder()\n .addAll(llmRequestBuilder.build().contents())\n .add(Content.fromParts(Part.fromText(prefix), artifact))\n .build());\n }\n}\n"], ["/adk-java/dev/src/main/java/com/google/adk/web/AdkWebServer.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.web;\n\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.google.adk.JsonBaseModel;\nimport com.google.adk.agents.BaseAgent;\nimport com.google.adk.agents.LiveRequest;\nimport com.google.adk.agents.LiveRequestQueue;\nimport com.google.adk.agents.RunConfig;\nimport com.google.adk.agents.RunConfig.StreamingMode;\nimport com.google.adk.artifacts.BaseArtifactService;\nimport com.google.adk.artifacts.InMemoryArtifactService;\nimport com.google.adk.artifacts.ListArtifactsResponse;\nimport com.google.adk.events.Event;\nimport com.google.adk.runner.Runner;\nimport com.google.adk.sessions.BaseSessionService;\nimport com.google.adk.sessions.InMemorySessionService;\nimport com.google.adk.sessions.ListSessionsResponse;\nimport com.google.adk.sessions.Session;\nimport com.google.adk.web.config.AgentLoadingProperties;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Lists;\nimport com.google.genai.types.Blob;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.FunctionCall;\nimport com.google.genai.types.FunctionResponse;\nimport com.google.genai.types.Modality;\nimport com.google.genai.types.Part;\nimport io.opentelemetry.api.OpenTelemetry;\nimport io.opentelemetry.api.common.AttributeKey;\nimport io.opentelemetry.api.common.Attributes;\nimport io.opentelemetry.api.trace.SpanId;\nimport io.opentelemetry.sdk.OpenTelemetrySdk;\nimport io.opentelemetry.sdk.common.CompletableResultCode;\nimport io.opentelemetry.sdk.resources.Resource;\nimport io.opentelemetry.sdk.trace.SdkTracerProvider;\nimport io.opentelemetry.sdk.trace.data.SpanData;\nimport io.opentelemetry.sdk.trace.export.SimpleSpanProcessor;\nimport io.opentelemetry.sdk.trace.export.SpanExporter;\nimport io.reactivex.rxjava3.core.Flowable;\nimport io.reactivex.rxjava3.core.Maybe;\nimport io.reactivex.rxjava3.core.Single;\nimport io.reactivex.rxjava3.disposables.Disposable;\nimport io.reactivex.rxjava3.schedulers.Schedulers;\nimport java.io.IOException;\nimport java.net.URI;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.Optional;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.stream.Collectors;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.beans.factory.annotation.Qualifier;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.boot.context.properties.ConfigurationPropertiesScan;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.ComponentScan;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.http.MediaType;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.stereotype.Component;\nimport org.springframework.util.MultiValueMap;\nimport org.springframework.web.bind.annotation.DeleteMapping;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.PostMapping;\nimport org.springframework.web.bind.annotation.RequestBody;\nimport org.springframework.web.bind.annotation.RequestParam;\nimport org.springframework.web.bind.annotation.RestController;\nimport org.springframework.web.server.ResponseStatusException;\nimport org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;\nimport org.springframework.web.servlet.config.annotation.ViewControllerRegistry;\nimport org.springframework.web.servlet.config.annotation.WebMvcConfigurer;\nimport org.springframework.web.servlet.mvc.method.annotation.SseEmitter;\nimport org.springframework.web.socket.CloseStatus;\nimport org.springframework.web.socket.TextMessage;\nimport org.springframework.web.socket.WebSocketSession;\nimport org.springframework.web.socket.config.annotation.EnableWebSocket;\nimport org.springframework.web.socket.config.annotation.WebSocketConfigurer;\nimport org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;\nimport org.springframework.web.socket.handler.TextWebSocketHandler;\nimport org.springframework.web.util.UriComponentsBuilder;\n\n/**\n * Single-file Spring Boot application for the Agent Server. Combines configuration, DTOs, and\n * controller logic.\n */\n@SpringBootApplication\n@ConfigurationPropertiesScan\n@ComponentScan(basePackages = {\"com.google.adk.web\", \"com.google.adk.web.config\"})\npublic class AdkWebServer implements WebMvcConfigurer {\n\n private static final Logger log = LoggerFactory.getLogger(AdkWebServer.class);\n\n @Value(\"${adk.web.ui.dir:#{null}}\")\n private String webUiDir;\n\n @Bean\n public BaseSessionService sessionService() {\n // TODO: Add logic to select service based on config (e.g., DB URL)\n log.info(\"Using InMemorySessionService\");\n return new InMemorySessionService();\n }\n\n /**\n * Provides the singleton instance of the ArtifactService (InMemory). TODO: configure this based\n * on config (e.g., DB URL)\n *\n * @return An instance of BaseArtifactService (currently InMemoryArtifactService).\n */\n @Bean\n public BaseArtifactService artifactService() {\n log.info(\"Using InMemoryArtifactService\");\n return new InMemoryArtifactService();\n }\n\n @Bean(\"loadedAgentRegistry\")\n public Map loadedAgentRegistry(\n AgentCompilerLoader loader, AgentLoadingProperties props) {\n if (props.getSourceDir() == null || props.getSourceDir().isEmpty()) {\n log.info(\"adk.agents.source-dir not set. Initializing with an empty agent registry.\");\n return Collections.emptyMap();\n }\n try {\n Map agents = loader.loadAgents();\n log.info(\"Loaded {} dynamic agent(s): {}\", agents.size(), agents.keySet());\n return agents;\n } catch (IOException e) {\n log.error(\"Failed to load dynamic agents\", e);\n return Collections.emptyMap();\n }\n }\n\n @Bean\n public ObjectMapper objectMapper() {\n return JsonBaseModel.getMapper();\n }\n\n /** Service for creating and caching Runner instances. */\n @Component\n public static class RunnerService {\n private static final Logger log = LoggerFactory.getLogger(RunnerService.class);\n\n private final Map agentRegistry;\n private final BaseArtifactService artifactService;\n private final BaseSessionService sessionService;\n private final Map runnerCache = new ConcurrentHashMap<>();\n\n @Autowired\n public RunnerService(\n @Qualifier(\"loadedAgentRegistry\") Map agentRegistry,\n BaseArtifactService artifactService,\n BaseSessionService sessionService) {\n this.agentRegistry = agentRegistry;\n this.artifactService = artifactService;\n this.sessionService = sessionService;\n }\n\n /**\n * Gets the Runner instance for a given application name. Handles potential agent engine ID\n * overrides.\n *\n * @param appName The application name requested by the user.\n * @return A configured Runner instance.\n */\n public Runner getRunner(String appName) {\n return runnerCache.computeIfAbsent(\n appName,\n key -> {\n BaseAgent agent = agentRegistry.get(key);\n if (agent == null) {\n log.error(\n \"Agent/App named '{}' not found in registry. Available apps: {}\",\n key,\n agentRegistry.keySet());\n throw new ResponseStatusException(\n HttpStatus.NOT_FOUND, \"Agent/App not found: \" + key);\n }\n log.info(\n \"RunnerService: Creating Runner for appName: {}, using agent\" + \" definition: {}\",\n appName,\n agent.name());\n return new Runner(agent, appName, this.artifactService, this.sessionService);\n });\n }\n }\n\n /** Configuration class for OpenTelemetry, setting up the tracer provider and span exporter. */\n @Configuration\n public static class OpenTelemetryConfig {\n private static final Logger otelLog = LoggerFactory.getLogger(OpenTelemetryConfig.class);\n\n @Bean\n public ApiServerSpanExporter apiServerSpanExporter() {\n return new ApiServerSpanExporter();\n }\n\n @Bean(destroyMethod = \"shutdown\")\n public SdkTracerProvider sdkTracerProvider(ApiServerSpanExporter apiServerSpanExporter) {\n otelLog.debug(\"Configuring SdkTracerProvider with ApiServerSpanExporter.\");\n Resource resource =\n Resource.getDefault()\n .merge(\n Resource.create(\n Attributes.of(AttributeKey.stringKey(\"service.name\"), \"adk-web-server\")));\n\n return SdkTracerProvider.builder()\n .addSpanProcessor(SimpleSpanProcessor.create(apiServerSpanExporter))\n .setResource(resource)\n .build();\n }\n\n @Bean\n public OpenTelemetry openTelemetrySdk(SdkTracerProvider sdkTracerProvider) {\n otelLog.debug(\"Configuring OpenTelemetrySdk and registering globally.\");\n OpenTelemetrySdk otelSdk =\n OpenTelemetrySdk.builder().setTracerProvider(sdkTracerProvider).buildAndRegisterGlobal();\n\n Runtime.getRuntime().addShutdownHook(new Thread(otelSdk::close));\n return otelSdk;\n }\n }\n\n /**\n * A custom SpanExporter that stores relevant span data. It handles two types of trace data\n * storage: 1. Event-ID based: Stores attributes of specific spans (call_llm, send_data,\n * tool_response) keyed by `gcp.vertex.agent.event_id`. This is used for debugging individual\n * events. 2. Session-ID based: Stores all exported spans and maintains a mapping from\n * `session_id` (extracted from `call_llm` spans) to a list of `trace_id`s. This is used for\n * retrieving all spans related to a session.\n */\n public static class ApiServerSpanExporter implements SpanExporter {\n private static final Logger exporterLog = LoggerFactory.getLogger(ApiServerSpanExporter.class);\n\n private final Map> eventIdTraceStorage = new ConcurrentHashMap<>();\n\n // Session ID -> Trace IDs -> Trace Object\n private final Map> sessionToTraceIdsMap = new ConcurrentHashMap<>();\n\n private final List allExportedSpans = Collections.synchronizedList(new ArrayList<>());\n\n public ApiServerSpanExporter() {}\n\n public Map getEventTraceAttributes(String eventId) {\n return this.eventIdTraceStorage.get(eventId);\n }\n\n public Map> getSessionToTraceIdsMap() {\n return this.sessionToTraceIdsMap;\n }\n\n public List getAllExportedSpans() {\n return this.allExportedSpans;\n }\n\n @Override\n public CompletableResultCode export(Collection spans) {\n exporterLog.debug(\"ApiServerSpanExporter received {} spans to export.\", spans.size());\n List currentBatch = new ArrayList<>(spans);\n allExportedSpans.addAll(currentBatch);\n\n for (SpanData span : currentBatch) {\n String spanName = span.getName();\n if (\"call_llm\".equals(spanName)\n || \"send_data\".equals(spanName)\n || (spanName != null && spanName.startsWith(\"tool_response\"))) {\n String eventId =\n span.getAttributes().get(AttributeKey.stringKey(\"gcp.vertex.agent.event_id\"));\n if (eventId != null && !eventId.isEmpty()) {\n Map attributesMap = new HashMap<>();\n span.getAttributes().forEach((key, value) -> attributesMap.put(key.getKey(), value));\n attributesMap.put(\"trace_id\", span.getSpanContext().getTraceId());\n attributesMap.put(\"span_id\", span.getSpanContext().getSpanId());\n attributesMap.putIfAbsent(\"gcp.vertex.agent.event_id\", eventId);\n exporterLog.debug(\"Storing event-based trace attributes for event_id: {}\", eventId);\n this.eventIdTraceStorage.put(eventId, attributesMap); // Use internal storage\n } else {\n exporterLog.trace(\n \"Span {} for event-based trace did not have 'gcp.vertex.agent.event_id'\"\n + \" attribute or it was empty.\",\n spanName);\n }\n }\n\n if (\"call_llm\".equals(spanName)) {\n String sessionId =\n span.getAttributes().get(AttributeKey.stringKey(\"gcp.vertex.agent.session_id\"));\n if (sessionId != null && !sessionId.isEmpty()) {\n String traceId = span.getSpanContext().getTraceId();\n sessionToTraceIdsMap\n .computeIfAbsent(sessionId, k -> Collections.synchronizedList(new ArrayList<>()))\n .add(traceId);\n exporterLog.trace(\n \"Associated trace_id {} with session_id {} for session tracing\",\n traceId,\n sessionId);\n } else {\n exporterLog.trace(\n \"Span {} for session trace did not have 'gcp.vertex.agent.session_id' attribute.\",\n spanName);\n }\n }\n }\n return CompletableResultCode.ofSuccess();\n }\n\n @Override\n public CompletableResultCode flush() {\n return CompletableResultCode.ofSuccess();\n }\n\n @Override\n public CompletableResultCode shutdown() {\n exporterLog.debug(\"Shutting down ApiServerSpanExporter.\");\n // no need to clear storage on shutdown, as everything is currently stored in memory.\n return CompletableResultCode.ofSuccess();\n }\n }\n\n /**\n * Data Transfer Object (DTO) for POST /run and POST /run-sse requests. Contains information\n * needed to execute an agent run.\n */\n public static class AgentRunRequest {\n @JsonProperty(\"appName\")\n public String appName;\n\n @JsonProperty(\"userId\")\n public String userId;\n\n @JsonProperty(\"sessionId\")\n public String sessionId;\n\n @JsonProperty(\"newMessage\")\n public Content newMessage;\n\n @JsonProperty(\"streaming\")\n public boolean streaming = false;\n\n public AgentRunRequest() {}\n\n public String getAppName() {\n return appName;\n }\n\n public String getUserId() {\n return userId;\n }\n\n public String getSessionId() {\n return sessionId;\n }\n\n public Content getNewMessage() {\n return newMessage;\n }\n\n public boolean getStreaming() {\n return streaming;\n }\n }\n\n /**\n * DTO for POST /apps/{appName}/eval_sets/{evalSetId}/add-session requests. Contains information\n * to associate a session with an evaluation set.\n */\n public static class AddSessionToEvalSetRequest {\n @JsonProperty(\"evalId\")\n public String evalId;\n\n @JsonProperty(\"sessionId\")\n public String sessionId;\n\n @JsonProperty(\"userId\")\n public String userId;\n\n public AddSessionToEvalSetRequest() {}\n\n public String getEvalId() {\n return evalId;\n }\n\n public String getSessionId() {\n return sessionId;\n }\n\n public String getUserId() {\n return userId;\n }\n }\n\n /**\n * DTO for POST /apps/{appName}/eval_sets/{evalSetId}/run-eval requests. Contains information for\n * running evaluations.\n */\n public static class RunEvalRequest {\n @JsonProperty(\"evalIds\")\n public List evalIds;\n\n @JsonProperty(\"evalMetrics\")\n public List evalMetrics;\n\n public RunEvalRequest() {}\n\n public List getEvalIds() {\n return evalIds;\n }\n\n public List getEvalMetrics() {\n return evalMetrics;\n }\n }\n\n /**\n * DTO for the response of POST /apps/{appName}/eval_sets/{evalSetId}/run-eval. Contains the\n * results of an evaluation run.\n */\n public static class RunEvalResult extends JsonBaseModel {\n @JsonProperty(\"appName\")\n public String appName;\n\n @JsonProperty(\"evalSetId\")\n public String evalSetId;\n\n @JsonProperty(\"evalId\")\n public String evalId;\n\n @JsonProperty(\"finalEvalStatus\")\n public String finalEvalStatus;\n\n @JsonProperty(\"evalMetricResults\")\n public List> evalMetricResults;\n\n @JsonProperty(\"sessionId\")\n public String sessionId;\n\n /**\n * Constructs a RunEvalResult.\n *\n * @param appName The application name.\n * @param evalSetId The evaluation set ID.\n * @param evalId The evaluation ID.\n * @param finalEvalStatus The final status of the evaluation.\n * @param evalMetricResults The results for each metric.\n * @param sessionId The session ID associated with the evaluation.\n */\n public RunEvalResult(\n String appName,\n String evalSetId,\n String evalId,\n String finalEvalStatus,\n List> evalMetricResults,\n String sessionId) {\n this.appName = appName;\n this.evalSetId = evalSetId;\n this.evalId = evalId;\n this.finalEvalStatus = finalEvalStatus;\n this.evalMetricResults = evalMetricResults;\n this.sessionId = sessionId;\n }\n\n public RunEvalResult() {}\n }\n\n /**\n * DTO for the response of GET\n * /apps/{appName}/users/{userId}/sessions/{sessionId}/events/{eventId}/graph. Contains the graph\n * representation (e.g., DOT source).\n */\n public static class GraphResponse {\n @JsonProperty(\"dotSrc\")\n public String dotSrc;\n\n /**\n * Constructs a GraphResponse.\n *\n * @param dotSrc The graph source string (e.g., in DOT format).\n */\n public GraphResponse(String dotSrc) {\n this.dotSrc = dotSrc;\n }\n\n public GraphResponse() {}\n\n public String getDotSrc() {\n return dotSrc;\n }\n }\n\n /**\n * Configures resource handlers for serving static content (like the Dev UI). Maps requests\n * starting with \"/dev-ui/\" to the directory specified by the 'adk.web.ui.dir' system property.\n */\n @Override\n public void addResourceHandlers(ResourceHandlerRegistry registry) {\n if (webUiDir != null && !webUiDir.isEmpty()) {\n // Ensure the path uses forward slashes and ends with a slash\n String location = webUiDir.replace(\"\\\\\", \"/\");\n if (!location.startsWith(\"file:\")) {\n location = \"file:\" + location; // Ensure file: prefix\n }\n if (!location.endsWith(\"/\")) {\n location += \"/\";\n }\n log.debug(\"Mapping URL path /** to static resources at location: {}\", location);\n registry\n .addResourceHandler(\"/**\")\n .addResourceLocations(location)\n .setCachePeriod(0)\n .resourceChain(true);\n\n } else {\n log.debug(\n \"System property 'adk.web.ui.dir' or config 'adk.web.ui.dir' is not set. Mapping URL path\"\n + \" /** to classpath:/browser/\");\n registry\n .addResourceHandler(\"/**\")\n .addResourceLocations(\"classpath:/browser/\")\n .setCachePeriod(0)\n .resourceChain(true);\n }\n }\n\n /**\n * Configures simple automated controllers: - Redirects the root path \"/\" to \"/dev-ui\". - Forwards\n * requests to \"/dev-ui\" to \"/dev-ui/index.html\" so the ResourceHandler serves it.\n */\n @Override\n public void addViewControllers(ViewControllerRegistry registry) {\n registry.addRedirectViewController(\"/\", \"/dev-ui\");\n registry.addViewController(\"/dev-ui\").setViewName(\"forward:/index.html\");\n registry.addViewController(\"/dev-ui/\").setViewName(\"forward:/index.html\");\n }\n\n /** Spring Boot REST Controller handling agent-related API endpoints. */\n @RestController\n public static class AgentController {\n\n private static final Logger log = LoggerFactory.getLogger(AgentController.class);\n\n private static final String EVAL_SESSION_ID_PREFIX = \"ADK_EVAL_\";\n\n private final BaseSessionService sessionService;\n private final BaseArtifactService artifactService;\n private final Map agentRegistry;\n private final ApiServerSpanExporter apiServerSpanExporter;\n private final RunnerService runnerService;\n private final ExecutorService sseExecutor = Executors.newCachedThreadPool();\n\n /**\n * Constructs the AgentController.\n *\n * @param sessionService The service for managing sessions.\n * @param artifactService The service for managing artifacts.\n * @param agentRegistry The registry of loaded agents.\n * @param apiServerSpanExporter The exporter holding all trace data.\n * @param runnerService The service for obtaining Runner instances.\n */\n @Autowired\n public AgentController(\n BaseSessionService sessionService,\n BaseArtifactService artifactService,\n @Qualifier(\"loadedAgentRegistry\") Map agentRegistry,\n ApiServerSpanExporter apiServerSpanExporter,\n RunnerService runnerService) {\n this.sessionService = sessionService;\n this.artifactService = artifactService;\n this.agentRegistry = agentRegistry;\n this.apiServerSpanExporter = apiServerSpanExporter;\n this.runnerService = runnerService;\n log.info(\n \"AgentController initialized with {} dynamic agents: {}\",\n agentRegistry.size(),\n agentRegistry.keySet());\n if (agentRegistry.isEmpty()) {\n log.warn(\n \"Agent registry is empty. Check 'adk.agents.source-dir' property and compilation\"\n + \" logs.\");\n }\n }\n\n /**\n * Finds a session by its identifiers or throws a ResponseStatusException if not found or if\n * there's an app/user mismatch.\n *\n * @param appName The application name.\n * @param userId The user ID.\n * @param sessionId The session ID.\n * @return The found Session object.\n * @throws ResponseStatusException with HttpStatus.NOT_FOUND if the session doesn't exist or\n * belongs to a different app/user.\n */\n private Session findSessionOrThrow(String appName, String userId, String sessionId) {\n Maybe maybeSession =\n sessionService.getSession(appName, userId, sessionId, Optional.empty());\n\n Session session = maybeSession.blockingGet();\n\n if (session == null) {\n log.warn(\n \"Session not found for appName={}, userId={}, sessionId={}\",\n appName,\n userId,\n sessionId);\n throw new ResponseStatusException(\n HttpStatus.NOT_FOUND,\n String.format(\n \"Session not found: appName=%s, userId=%s, sessionId=%s\",\n appName, userId, sessionId));\n }\n\n if (!Objects.equals(session.appName(), appName)\n || !Objects.equals(session.userId(), userId)) {\n log.warn(\n \"Session ID {} found but appName/userId mismatch (Expected: {}/{}, Found: {}/{}) -\"\n + \" Treating as not found.\",\n sessionId,\n appName,\n userId,\n session.appName(),\n session.userId());\n\n throw new ResponseStatusException(\n HttpStatus.NOT_FOUND, \"Session found but belongs to a different app/user.\");\n }\n log.debug(\"Found session: {}\", sessionId);\n return session;\n }\n\n /**\n * Lists available applications. Currently returns only the configured root agent's name.\n *\n * @return A list containing the root agent's name.\n */\n @GetMapping(\"/list-apps\")\n public List listApps() {\n log.info(\"Listing apps from dynamic registry. Found: {}\", agentRegistry.keySet());\n List appNames = new ArrayList<>(agentRegistry.keySet());\n Collections.sort(appNames);\n return appNames;\n }\n\n /**\n * Endpoint for retrieving trace information stored by the ApiServerSpanExporter, based on event\n * ID.\n *\n * @param eventId The ID of the event to trace (expected to be gcp.vertex.agent.event_id).\n * @return A ResponseEntity containing the trace data or NOT_FOUND.\n */\n @GetMapping(\"/debug/trace/{eventId}\")\n public ResponseEntity getTraceDict(@PathVariable String eventId) {\n log.info(\"Request received for GET /debug/trace/{}\", eventId);\n Map traceData = this.apiServerSpanExporter.getEventTraceAttributes(eventId);\n if (traceData == null) {\n log.warn(\"Trace not found for eventId: {}\", eventId);\n return ResponseEntity.status(HttpStatus.NOT_FOUND)\n .body(Collections.singletonMap(\"message\", \"Trace not found for eventId: \" + eventId));\n }\n log.info(\"Returning trace data for eventId: {}\", eventId);\n return ResponseEntity.ok(traceData);\n }\n\n /**\n * Retrieves trace spans for a given session ID.\n *\n * @param sessionId The session ID.\n * @return A ResponseEntity containing a list of span data maps for the session, or an empty\n * list.\n */\n @GetMapping(\"/debug/trace/session/{sessionId}\")\n public ResponseEntity getSessionTrace(@PathVariable String sessionId) {\n log.info(\"Request received for GET /debug/trace/session/{}\", sessionId);\n\n List traceIdsForSession =\n this.apiServerSpanExporter.getSessionToTraceIdsMap().get(sessionId);\n\n if (traceIdsForSession == null || traceIdsForSession.isEmpty()) {\n log.warn(\"No trace IDs found for session ID: {}\", sessionId);\n return ResponseEntity.ok(Collections.emptyList());\n }\n\n // Iterate over a snapshot of all spans to avoid concurrent modification issues\n // if the exporter is actively adding spans.\n List allSpansSnapshot =\n new ArrayList<>(this.apiServerSpanExporter.getAllExportedSpans());\n\n if (allSpansSnapshot.isEmpty()) {\n log.warn(\"No spans have been exported yet overall.\");\n return ResponseEntity.ok(Collections.emptyList());\n }\n\n Set relevantTraceIds = new HashSet<>(traceIdsForSession);\n List> resultSpans = new ArrayList<>();\n\n for (SpanData span : allSpansSnapshot) {\n if (relevantTraceIds.contains(span.getSpanContext().getTraceId())) {\n Map spanMap = new HashMap<>();\n spanMap.put(\"name\", span.getName());\n spanMap.put(\"span_id\", span.getSpanContext().getSpanId());\n spanMap.put(\"trace_id\", span.getSpanContext().getTraceId());\n spanMap.put(\"start_time\", span.getStartEpochNanos());\n spanMap.put(\"end_time\", span.getEndEpochNanos());\n\n Map attributesMap = new HashMap<>();\n span.getAttributes().forEach((key, value) -> attributesMap.put(key.getKey(), value));\n spanMap.put(\"attributes\", attributesMap);\n\n String parentSpanId = span.getParentSpanId();\n if (SpanId.isValid(parentSpanId)) {\n spanMap.put(\"parent_span_id\", parentSpanId);\n } else {\n spanMap.put(\"parent_span_id\", null);\n }\n resultSpans.add(spanMap);\n }\n }\n\n log.info(\"Returning {} spans for session ID: {}\", resultSpans.size(), sessionId);\n return ResponseEntity.ok(resultSpans);\n }\n\n /**\n * Retrieves a specific session by its ID.\n *\n * @param appName The application name.\n * @param userId The user ID.\n * @param sessionId The session ID.\n * @return The requested Session object.\n * @throws ResponseStatusException if the session is not found.\n */\n @GetMapping(\"/apps/{appName}/users/{userId}/sessions/{sessionId}\")\n public Session getSession(\n @PathVariable String appName, @PathVariable String userId, @PathVariable String sessionId) {\n log.info(\n \"Request received for GET /apps/{}/users/{}/sessions/{}\", appName, userId, sessionId);\n return findSessionOrThrow(appName, userId, sessionId);\n }\n\n /**\n * Lists all non-evaluation sessions for a given app and user.\n *\n * @param appName The name of the application.\n * @param userId The ID of the user.\n * @return A list of sessions, excluding those used for evaluation.\n */\n @GetMapping(\"/apps/{appName}/users/{userId}/sessions\")\n public List listSessions(@PathVariable String appName, @PathVariable String userId) {\n log.info(\"Request received for GET /apps/{}/users/{}/sessions\", appName, userId);\n\n Single sessionsResponseSingle =\n sessionService.listSessions(appName, userId);\n\n ListSessionsResponse response = sessionsResponseSingle.blockingGet();\n if (response == null || response.sessions() == null) {\n log.warn(\n \"Received null response or null sessions list for listSessions({}, {})\",\n appName,\n userId);\n return Collections.emptyList();\n }\n\n List filteredSessions =\n response.sessions().stream()\n .filter(s -> !s.id().startsWith(EVAL_SESSION_ID_PREFIX))\n .collect(Collectors.toList());\n log.info(\n \"Found {} non-evaluation sessions for app={}, user={}\",\n filteredSessions.size(),\n appName,\n userId);\n return filteredSessions;\n }\n\n /**\n * Creates a new session with a specific ID provided by the client.\n *\n * @param appName The application name.\n * @param userId The user ID.\n * @param sessionId The desired session ID.\n * @param state Optional initial state for the session.\n * @return The newly created Session object.\n * @throws ResponseStatusException if a session with the given ID already exists (BAD_REQUEST)\n * or if creation fails (INTERNAL_SERVER_ERROR).\n */\n @PostMapping(\"/apps/{appName}/users/{userId}/sessions/{sessionId}\")\n public Session createSessionWithId(\n @PathVariable String appName,\n @PathVariable String userId,\n @PathVariable String sessionId,\n @RequestBody(required = false) Map state) {\n log.info(\n \"Request received for POST /apps/{}/users/{}/sessions/{} with state: {}\",\n appName,\n userId,\n sessionId,\n state);\n\n try {\n findSessionOrThrow(appName, userId, sessionId);\n\n log.warn(\"Attempted to create session with existing ID: {}\", sessionId);\n throw new ResponseStatusException(\n HttpStatus.BAD_REQUEST, \"Session already exists: \" + sessionId);\n } catch (ResponseStatusException e) {\n\n if (e.getStatusCode() != HttpStatus.NOT_FOUND) {\n throw e;\n }\n\n log.info(\"Session {} not found, proceeding with creation.\", sessionId);\n }\n\n Map initialState = (state != null) ? state : Collections.emptyMap();\n try {\n Session createdSession =\n sessionService\n .createSession(appName, userId, new ConcurrentHashMap<>(initialState), sessionId)\n .blockingGet();\n\n if (createdSession == null) {\n\n log.error(\n \"Session creation call completed without error but returned null session for {}\",\n sessionId);\n throw new ResponseStatusException(\n HttpStatus.INTERNAL_SERVER_ERROR, \"Failed to create session (null result)\");\n }\n log.info(\"Session created successfully with id: {}\", createdSession.id());\n return createdSession;\n } catch (Exception e) {\n log.error(\"Error creating session with id {}\", sessionId, e);\n\n throw new ResponseStatusException(\n HttpStatus.INTERNAL_SERVER_ERROR, \"Error creating session\", e);\n }\n }\n\n /**\n * Creates a new session where the ID is generated by the service.\n *\n * @param appName The application name.\n * @param userId The user ID.\n * @param state Optional initial state for the session.\n * @return The newly created Session object.\n * @throws ResponseStatusException if creation fails (INTERNAL_SERVER_ERROR).\n */\n @PostMapping(\"/apps/{appName}/users/{userId}/sessions\")\n public Session createSession(\n @PathVariable String appName,\n @PathVariable String userId,\n @RequestBody(required = false) Map state) {\n\n log.info(\n \"Request received for POST /apps/{}/users/{}/sessions (service generates ID) with state:\"\n + \" {}\",\n appName,\n userId,\n state);\n\n Map initialState = (state != null) ? state : Collections.emptyMap();\n try {\n\n Session createdSession =\n sessionService\n .createSession(appName, userId, new ConcurrentHashMap<>(initialState), null)\n .blockingGet();\n\n if (createdSession == null) {\n log.error(\n \"Session creation call completed without error but returned null session for user {}\",\n userId);\n throw new ResponseStatusException(\n HttpStatus.INTERNAL_SERVER_ERROR, \"Failed to create session (null result)\");\n }\n log.info(\"Session created successfully with generated id: {}\", createdSession.id());\n return createdSession;\n } catch (Exception e) {\n log.error(\"Error creating session for user {}\", userId, e);\n throw new ResponseStatusException(\n HttpStatus.INTERNAL_SERVER_ERROR, \"Error creating session\", e);\n }\n }\n\n /**\n * Deletes a specific session.\n *\n * @param appName The application name.\n * @param userId The user ID.\n * @param sessionId The session ID to delete.\n * @return A ResponseEntity with status NO_CONTENT on success.\n * @throws ResponseStatusException if deletion fails (INTERNAL_SERVER_ERROR).\n */\n @DeleteMapping(\"/apps/{appName}/users/{userId}/sessions/{sessionId}\")\n public ResponseEntity deleteSession(\n @PathVariable String appName, @PathVariable String userId, @PathVariable String sessionId) {\n log.info(\n \"Request received for DELETE /apps/{}/users/{}/sessions/{}\", appName, userId, sessionId);\n try {\n\n sessionService.deleteSession(appName, userId, sessionId).blockingAwait();\n log.info(\"Session deleted successfully: {}\", sessionId);\n return ResponseEntity.noContent().build();\n } catch (Exception e) {\n\n log.error(\"Error deleting session {}\", sessionId, e);\n\n throw new ResponseStatusException(\n HttpStatus.INTERNAL_SERVER_ERROR, \"Error deleting session\", e);\n }\n }\n\n /**\n * Loads the latest or a specific version of an artifact associated with a session.\n *\n * @param appName The application name.\n * @param userId The user ID.\n * @param sessionId The session ID.\n * @param artifactName The name of the artifact.\n * @param version Optional specific version number. If null, loads the latest.\n * @return The artifact content as a Part object.\n * @throws ResponseStatusException if the artifact is not found (NOT_FOUND).\n */\n @GetMapping(\"/apps/{appName}/users/{userId}/sessions/{sessionId}/artifacts/{artifactName}\")\n public Part loadArtifact(\n @PathVariable String appName,\n @PathVariable String userId,\n @PathVariable String sessionId,\n @PathVariable String artifactName,\n @RequestParam(required = false) Integer version) {\n String versionStr = (version == null) ? \"latest\" : String.valueOf(version);\n log.info(\n \"Request received to load artifact: app={}, user={}, session={}, artifact={}, version={}\",\n appName,\n userId,\n sessionId,\n artifactName,\n versionStr);\n\n Maybe artifactMaybe =\n artifactService.loadArtifact(\n appName, userId, sessionId, artifactName, Optional.ofNullable(version));\n\n Part artifact = artifactMaybe.blockingGet();\n\n if (artifact == null) {\n log.warn(\n \"Artifact not found: app={}, user={}, session={}, artifact={}, version={}\",\n appName,\n userId,\n sessionId,\n artifactName,\n versionStr);\n throw new ResponseStatusException(HttpStatus.NOT_FOUND, \"Artifact not found\");\n }\n log.debug(\"Artifact {} version {} loaded successfully.\", artifactName, versionStr);\n return artifact;\n }\n\n /**\n * Loads a specific version of an artifact.\n *\n * @param appName The application name.\n * @param userId The user ID.\n * @param sessionId The session ID.\n * @param artifactName The name of the artifact.\n * @param versionId The specific version number.\n * @return The artifact content as a Part object.\n * @throws ResponseStatusException if the artifact version is not found (NOT_FOUND).\n */\n @GetMapping(\n \"/apps/{appName}/users/{userId}/sessions/{sessionId}/artifacts/{artifactName}/versions/{versionId}\")\n public Part loadArtifactVersion(\n @PathVariable String appName,\n @PathVariable String userId,\n @PathVariable String sessionId,\n @PathVariable String artifactName,\n @PathVariable int versionId) {\n log.info(\n \"Request received to load artifact version: app={}, user={}, session={}, artifact={},\"\n + \" version={}\",\n appName,\n userId,\n sessionId,\n artifactName,\n versionId);\n\n Maybe artifactMaybe =\n artifactService.loadArtifact(\n appName, userId, sessionId, artifactName, Optional.of(versionId));\n\n Part artifact = artifactMaybe.blockingGet();\n\n if (artifact == null) {\n log.warn(\n \"Artifact version not found: app={}, user={}, session={}, artifact={}, version={}\",\n appName,\n userId,\n sessionId,\n artifactName,\n versionId);\n throw new ResponseStatusException(HttpStatus.NOT_FOUND, \"Artifact version not found\");\n }\n log.debug(\"Artifact {} version {} loaded successfully.\", artifactName, versionId);\n return artifact;\n }\n\n /**\n * Lists the names of all artifacts associated with a session.\n *\n * @param appName The application name.\n * @param userId The user ID.\n * @param sessionId The session ID.\n * @return A list of artifact names.\n */\n @GetMapping(\"/apps/{appName}/users/{userId}/sessions/{sessionId}/artifacts\")\n public List listArtifactNames(\n @PathVariable String appName, @PathVariable String userId, @PathVariable String sessionId) {\n log.info(\n \"Request received to list artifact names for app={}, user={}, session={}\",\n appName,\n userId,\n sessionId);\n\n Single responseSingle =\n artifactService.listArtifactKeys(appName, userId, sessionId);\n\n ListArtifactsResponse response = responseSingle.blockingGet();\n List filenames =\n (response != null && response.filenames() != null)\n ? response.filenames()\n : Collections.emptyList();\n log.info(\"Found {} artifact names for session {}\", filenames.size(), sessionId);\n return filenames;\n }\n\n /**\n * Lists the available versions for a specific artifact.\n *\n * @param appName The application name.\n * @param userId The user ID.\n * @param sessionId The session ID.\n * @param artifactName The name of the artifact.\n * @return A list of version numbers (integers).\n */\n @GetMapping(\n \"/apps/{appName}/users/{userId}/sessions/{sessionId}/artifacts/{artifactName}/versions\")\n public List listArtifactVersions(\n @PathVariable String appName,\n @PathVariable String userId,\n @PathVariable String sessionId,\n @PathVariable String artifactName) {\n log.info(\n \"Request received to list versions for artifact: app={}, user={}, session={},\"\n + \" artifact={}\",\n appName,\n userId,\n sessionId,\n artifactName);\n\n Single> versionsSingle =\n artifactService.listVersions(appName, userId, sessionId, artifactName);\n ImmutableList versions = versionsSingle.blockingGet();\n log.info(\n \"Found {} versions for artifact {}\",\n versions != null ? versions.size() : 0,\n artifactName);\n return versions != null ? versions : Collections.emptyList();\n }\n\n /**\n * Deletes an artifact and all its versions.\n *\n * @param appName The application name.\n * @param userId The user ID.\n * @param sessionId The session ID.\n * @param artifactName The name of the artifact to delete.\n * @return A ResponseEntity with status NO_CONTENT on success.\n * @throws ResponseStatusException if deletion fails (INTERNAL_SERVER_ERROR).\n */\n @DeleteMapping(\"/apps/{appName}/users/{userId}/sessions/{sessionId}/artifacts/{artifactName}\")\n public ResponseEntity deleteArtifact(\n @PathVariable String appName,\n @PathVariable String userId,\n @PathVariable String sessionId,\n @PathVariable String artifactName) {\n log.info(\n \"Request received to delete artifact: app={}, user={}, session={}, artifact={}\",\n appName,\n userId,\n sessionId,\n artifactName);\n\n try {\n\n artifactService.deleteArtifact(appName, userId, sessionId, artifactName);\n log.info(\"Artifact deleted successfully: {}\", artifactName);\n return ResponseEntity.noContent().build();\n } catch (Exception e) {\n log.error(\"Error deleting artifact {}\", artifactName, e);\n\n throw new ResponseStatusException(\n HttpStatus.INTERNAL_SERVER_ERROR, \"Error deleting artifact\", e);\n }\n }\n\n /**\n * Executes a non-streaming agent run for a given session and message.\n *\n * @param request The AgentRunRequest containing run details.\n * @return A list of events generated during the run.\n * @throws ResponseStatusException if the session is not found or the run fails.\n */\n @PostMapping(\"/run\")\n public List agentRun(@RequestBody AgentRunRequest request) {\n if (request.appName == null || request.appName.trim().isEmpty()) {\n log.warn(\"appName cannot be null or empty in POST /run request.\");\n throw new ResponseStatusException(\n HttpStatus.BAD_REQUEST, \"appName cannot be null or empty\");\n }\n if (request.sessionId == null || request.sessionId.trim().isEmpty()) {\n log.warn(\"sessionId cannot be null or empty in POST /run request.\");\n throw new ResponseStatusException(\n HttpStatus.BAD_REQUEST, \"sessionId cannot be null or empty\");\n }\n log.info(\"Request received for POST /run for session: {}\", request.sessionId);\n\n Runner runner = this.runnerService.getRunner(request.appName);\n try {\n\n RunConfig runConfig = RunConfig.builder().setStreamingMode(StreamingMode.NONE).build();\n Flowable eventStream =\n runner.runAsync(request.userId, request.sessionId, request.newMessage, runConfig);\n\n List events = Lists.newArrayList(eventStream.blockingIterable());\n log.info(\"Agent run for session {} generated {} events.\", request.sessionId, events.size());\n return events;\n } catch (Exception e) {\n log.error(\"Error during agent run for session {}\", request.sessionId, e);\n throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, \"Agent run failed\", e);\n }\n }\n\n /**\n * Executes an agent run and streams the resulting events using Server-Sent Events (SSE).\n *\n * @param request The AgentRunRequest containing run details.\n * @return A Flux that will stream events to the client.\n */\n @PostMapping(value = \"/run_sse\", produces = MediaType.TEXT_EVENT_STREAM_VALUE)\n public SseEmitter agentRunSse(@RequestBody AgentRunRequest request) {\n SseEmitter emitter = new SseEmitter();\n\n if (request.appName == null || request.appName.trim().isEmpty()) {\n log.warn(\n \"appName cannot be null or empty in SseEmitter request for appName: {}, session: {}\",\n request.appName,\n request.sessionId);\n emitter.completeWithError(\n new ResponseStatusException(HttpStatus.BAD_REQUEST, \"appName cannot be null or empty\"));\n return emitter;\n }\n if (request.sessionId == null || request.sessionId.trim().isEmpty()) {\n log.warn(\n \"sessionId cannot be null or empty in SseEmitter request for appName: {}, session: {}\",\n request.appName,\n request.sessionId);\n emitter.completeWithError(\n new ResponseStatusException(\n HttpStatus.BAD_REQUEST, \"sessionId cannot be null or empty\"));\n return emitter;\n }\n\n log.info(\n \"SseEmitter Request received for POST /run_sse_emitter for session: {}\",\n request.sessionId);\n\n final String sessionId = request.sessionId;\n sseExecutor.execute(\n () -> {\n Runner runner;\n try {\n runner = this.runnerService.getRunner(request.appName);\n } catch (ResponseStatusException e) {\n log.warn(\n \"Setup failed for SseEmitter request for session {}: {}\",\n sessionId,\n e.getMessage());\n try {\n emitter.completeWithError(e);\n } catch (Exception ex) {\n log.warn(\n \"Error completing emitter after setup failure for session {}: {}\",\n sessionId,\n ex.getMessage());\n }\n return;\n }\n\n final RunConfig runConfig =\n RunConfig.builder()\n .setStreamingMode(\n request.getStreaming() ? StreamingMode.SSE : StreamingMode.NONE)\n .build();\n\n Flowable eventFlowable =\n runner.runAsync(request.userId, request.sessionId, request.newMessage, runConfig);\n\n Disposable disposable =\n eventFlowable\n .observeOn(Schedulers.io())\n .subscribe(\n event -> {\n try {\n log.debug(\n \"SseEmitter: Sending event {} for session {}\",\n event.id(),\n sessionId);\n emitter.send(SseEmitter.event().data(event.toJson()));\n } catch (IOException e) {\n log.error(\n \"SseEmitter: IOException sending event for session {}: {}\",\n sessionId,\n e.getMessage());\n throw new RuntimeException(\"Failed to send event\", e);\n } catch (Exception e) {\n log.error(\n \"SseEmitter: Unexpected error sending event for session {}: {}\",\n sessionId,\n e.getMessage(),\n e);\n throw new RuntimeException(\"Unexpected error sending event\", e);\n }\n },\n error -> {\n log.error(\n \"SseEmitter: Stream error for session {}: {}\",\n sessionId,\n error.getMessage(),\n error);\n try {\n emitter.completeWithError(error);\n } catch (Exception ex) {\n log.warn(\n \"Error completing emitter after stream error for session {}: {}\",\n sessionId,\n ex.getMessage());\n }\n },\n () -> {\n log.debug(\n \"SseEmitter: Stream completed normally for session: {}\", sessionId);\n try {\n emitter.complete();\n } catch (Exception ex) {\n log.warn(\n \"Error completing emitter after normal completion for session {}:\"\n + \" {}\",\n sessionId,\n ex.getMessage());\n }\n });\n emitter.onCompletion(\n () -> {\n log.debug(\n \"SseEmitter: onCompletion callback for session: {}. Disposing subscription.\",\n sessionId);\n if (!disposable.isDisposed()) {\n disposable.dispose();\n }\n });\n emitter.onTimeout(\n () -> {\n log.debug(\n \"SseEmitter: onTimeout callback for session: {}. Disposing subscription and\"\n + \" completing.\",\n sessionId);\n if (!disposable.isDisposed()) {\n disposable.dispose();\n }\n emitter.complete();\n });\n });\n\n log.debug(\"SseEmitter: Returning emitter for session: {}\", sessionId);\n return emitter;\n }\n\n /**\n * Endpoint to get a graph representation of an event (currently returns a placeholder).\n * Requires Graphviz or similar tooling for full implementation.\n *\n * @param appName Application name.\n * @param userId User ID.\n * @param sessionId Session ID.\n * @param eventId Event ID.\n * @return ResponseEntity containing a GraphResponse with placeholder DOT source.\n * @throws ResponseStatusException if the session or event is not found.\n */\n @GetMapping(\"/apps/{appName}/users/{userId}/sessions/{sessionId}/events/{eventId}/graph\")\n public ResponseEntity getEventGraph(\n @PathVariable String appName,\n @PathVariable String userId,\n @PathVariable String sessionId,\n @PathVariable String eventId) {\n log.info(\n \"Request received for GET /apps/{}/users/{}/sessions/{}/events/{}/graph\",\n appName,\n userId,\n sessionId,\n eventId);\n\n BaseAgent currentAppAgent = agentRegistry.get(appName);\n if (currentAppAgent == null) {\n log.warn(\"Agent app '{}' not found for graph generation.\", appName);\n return ResponseEntity.status(HttpStatus.NOT_FOUND)\n .body(new GraphResponse(\"Agent app not found: \" + appName));\n }\n\n Session session = findSessionOrThrow(appName, userId, sessionId);\n Event event =\n session.events().stream()\n .filter(e -> Objects.equals(e.id(), eventId))\n .findFirst()\n .orElse(null);\n\n if (event == null) {\n log.warn(\"Event {} not found in session {}\", eventId, sessionId);\n return ResponseEntity.ok(new GraphResponse(null));\n }\n\n log.debug(\"Found event {} for graph generation.\", eventId);\n\n List> highlightPairs = new ArrayList<>();\n String eventAuthor = event.author();\n List functionCalls = event.functionCalls();\n List functionResponses = event.functionResponses();\n\n if (!functionCalls.isEmpty()) {\n log.debug(\"Processing {} function calls for highlighting.\", functionCalls.size());\n for (FunctionCall fc : functionCalls) {\n Optional toolName = fc.name();\n if (toolName.isPresent() && !toolName.get().isEmpty()) {\n highlightPairs.add(ImmutableList.of(eventAuthor, toolName.get()));\n log.trace(\"Adding function call highlight: {} -> {}\", eventAuthor, toolName.get());\n }\n }\n } else if (!functionResponses.isEmpty()) {\n log.debug(\"Processing {} function responses for highlighting.\", functionResponses.size());\n for (FunctionResponse fr : functionResponses) {\n Optional toolName = fr.name();\n if (toolName.isPresent() && !toolName.get().isEmpty()) {\n highlightPairs.add(ImmutableList.of(toolName.get(), eventAuthor));\n log.trace(\"Adding function response highlight: {} -> {}\", toolName.get(), eventAuthor);\n }\n }\n } else {\n log.debug(\"Processing simple event, highlighting author: {}\", eventAuthor);\n highlightPairs.add(ImmutableList.of(eventAuthor, eventAuthor));\n }\n\n Optional dotSourceOpt =\n AgentGraphGenerator.getAgentGraphDotSource(currentAppAgent, highlightPairs);\n\n if (dotSourceOpt.isPresent()) {\n log.debug(\"Successfully generated graph DOT source for event {}\", eventId);\n return ResponseEntity.ok(new GraphResponse(dotSourceOpt.get()));\n } else {\n log.warn(\n \"Failed to generate graph DOT source for event {} with agent {}\",\n eventId,\n currentAppAgent.name());\n return ResponseEntity.ok(new GraphResponse(\"Could not generate graph for this event.\"));\n }\n }\n\n /** Placeholder for creating an evaluation set. */\n @PostMapping(\"/apps/{appName}/eval_sets/{evalSetId}\")\n public ResponseEntity createEvalSet(\n @PathVariable String appName, @PathVariable String evalSetId) {\n log.warn(\"Endpoint /apps/{}/eval_sets/{} (POST) is not implemented\", appName, evalSetId);\n return ResponseEntity.status(HttpStatus.NOT_IMPLEMENTED)\n .body(Collections.singletonMap(\"message\", \"Eval set creation not implemented\"));\n }\n\n /** Placeholder for listing evaluation sets. */\n @GetMapping(\"/apps/{appName}/eval_sets\")\n public List listEvalSets(@PathVariable String appName) {\n log.warn(\"Endpoint /apps/{}/eval_sets (GET) is not implemented\", appName);\n return Collections.emptyList();\n }\n\n /** Placeholder for adding a session to an evaluation set. */\n @PostMapping(\"/apps/{appName}/eval_sets/{evalSetId}/add-session\")\n public ResponseEntity addSessionToEvalSet(\n @PathVariable String appName,\n @PathVariable String evalSetId,\n @RequestBody AddSessionToEvalSetRequest req) {\n log.warn(\n \"Endpoint /apps/{}/eval_sets/{}/add-session is not implemented. Request details:\"\n + \" evalId={}, sessionId={}, userId={}\",\n appName,\n evalSetId,\n req.getEvalId(),\n req.getSessionId(),\n req.getUserId());\n return ResponseEntity.status(HttpStatus.NOT_IMPLEMENTED)\n .body(Collections.singletonMap(\"message\", \"Adding session to eval set not implemented\"));\n }\n\n /** Placeholder for listing evaluations within an evaluation set. */\n @GetMapping(\"/apps/{appName}/eval_sets/{evalSetId}/evals\")\n public List listEvalsInEvalSet(\n @PathVariable String appName, @PathVariable String evalSetId) {\n log.warn(\"Endpoint /apps/{}/eval_sets/{}/evals is not implemented\", appName, evalSetId);\n return Collections.emptyList();\n }\n\n /** Placeholder for running evaluations. */\n @PostMapping(\"/apps/{appName}/eval_sets/{evalSetId}/run-eval\")\n public List runEval(\n @PathVariable String appName,\n @PathVariable String evalSetId,\n @RequestBody RunEvalRequest req) {\n log.warn(\n \"Endpoint /apps/{}/eval_sets/{}/run-eval is not implemented. Request details: evalIds={},\"\n + \" evalMetrics={}\",\n appName,\n evalSetId,\n req.getEvalIds(),\n req.getEvalMetrics());\n return Collections.emptyList();\n }\n\n /**\n * Gets a specific evaluation result. (STUB - Not Implemented)\n *\n * @param appName The application name.\n * @param evalResultId The evaluation result ID.\n * @return A ResponseEntity indicating the endpoint is not implemented.\n */\n @GetMapping(\"/apps/{appName}/eval_results/{evalResultId}\")\n public ResponseEntity getEvalResult(\n @PathVariable String appName, @PathVariable String evalResultId) {\n log.warn(\"Endpoint /apps/{}/eval_results/{} (GET) is not implemented\", appName, evalResultId);\n return ResponseEntity.status(HttpStatus.NOT_IMPLEMENTED)\n .body(Collections.singletonMap(\"message\", \"Get evaluation result not implemented\"));\n }\n\n /**\n * Lists all evaluation results for an app. (STUB - Not Implemented)\n *\n * @param appName The application name.\n * @return An empty list, as this endpoint is not implemented.\n */\n @GetMapping(\"/apps/{appName}/eval_results\")\n public List listEvalResults(@PathVariable String appName) {\n log.warn(\"Endpoint /apps/{}/eval_results (GET) is not implemented\", appName);\n return Collections.emptyList();\n }\n }\n\n /** Configuration class for WebSocket handling. */\n @Configuration\n @EnableWebSocket\n public static class WebSocketConfig implements WebSocketConfigurer {\n\n private final LiveWebSocketHandler liveWebSocketHandler;\n\n @Autowired\n public WebSocketConfig(LiveWebSocketHandler liveWebSocketHandler) {\n this.liveWebSocketHandler = liveWebSocketHandler;\n }\n\n @Override\n public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {\n registry.addHandler(liveWebSocketHandler, \"/run_live\").setAllowedOrigins(\"*\");\n }\n }\n\n /**\n * WebSocket Handler for the /run_live endpoint.\n *\n *

Manages bidirectional communication for live agent interactions. Assumes the\n * com.google.adk.runner.Runner class has a method: {@code public Flowable runLive(Session\n * session, Flowable liveRequests, List modalities)}\n */\n @Component\n public static class LiveWebSocketHandler extends TextWebSocketHandler {\n private static final Logger log = LoggerFactory.getLogger(LiveWebSocketHandler.class);\n private static final String LIVE_REQUEST_QUEUE_ATTR = \"liveRequestQueue\";\n private static final String LIVE_SUBSCRIPTION_ATTR = \"liveSubscription\";\n private static final int WEBSOCKET_MAX_BYTES_FOR_REASON = 123;\n\n private final ObjectMapper objectMapper;\n private final BaseSessionService sessionService;\n private final RunnerService runnerService;\n\n @Autowired\n public LiveWebSocketHandler(\n ObjectMapper objectMapper, BaseSessionService sessionService, RunnerService runnerService) {\n this.objectMapper = objectMapper;\n this.sessionService = sessionService;\n this.runnerService = runnerService;\n }\n\n @Override\n public void afterConnectionEstablished(WebSocketSession wsSession) throws Exception {\n URI uri = wsSession.getUri();\n if (uri == null) {\n log.warn(\"WebSocket session URI is null, cannot establish connection.\");\n wsSession.close(CloseStatus.SERVER_ERROR.withReason(\"Invalid URI\"));\n return;\n }\n String path = uri.getPath();\n log.info(\"WebSocket connection established: {} from {}\", wsSession.getId(), uri);\n\n MultiValueMap queryParams =\n UriComponentsBuilder.fromUri(uri).build().getQueryParams();\n String appName = queryParams.getFirst(\"app_name\");\n String userId = queryParams.getFirst(\"user_id\");\n String sessionId = queryParams.getFirst(\"session_id\");\n\n if (appName == null || appName.trim().isEmpty()) {\n log.warn(\n \"WebSocket connection for session {} rejected: app_name query parameter is required and\"\n + \" cannot be empty. URI: {}\",\n wsSession.getId(),\n uri);\n wsSession.close(\n CloseStatus.POLICY_VIOLATION.withReason(\n \"app_name query parameter is required and cannot be empty\"));\n return;\n }\n if (sessionId == null || sessionId.trim().isEmpty()) {\n log.warn(\n \"WebSocket connection for session {} rejected: session_id query parameter is required\"\n + \" and cannot be empty. URI: {}\",\n wsSession.getId(),\n uri);\n wsSession.close(\n CloseStatus.POLICY_VIOLATION.withReason(\n \"session_id query parameter is required and cannot be empty\"));\n return;\n }\n\n log.debug(\n \"Extracted params for WebSocket session {}: appName={}, userId={}, sessionId={},\",\n wsSession.getId(),\n appName,\n userId,\n sessionId);\n\n RunConfig runConfig =\n RunConfig.builder()\n .setResponseModalities(ImmutableList.of(new Modality(Modality.Known.AUDIO)))\n .setStreamingMode(StreamingMode.BIDI)\n .build();\n\n Session session;\n try {\n session =\n sessionService.getSession(appName, userId, sessionId, Optional.empty()).blockingGet();\n if (session == null) {\n log.warn(\n \"Session not found for WebSocket: app={}, user={}, id={}. Closing connection.\",\n appName,\n userId,\n sessionId);\n wsSession.close(new CloseStatus(1002, \"Session not found\")); // 1002: Protocol Error\n return;\n }\n } catch (Exception e) {\n log.error(\n \"Error retrieving session for WebSocket: app={}, user={}, id={}\",\n appName,\n userId,\n sessionId,\n e);\n wsSession.close(CloseStatus.SERVER_ERROR.withReason(\"Failed to retrieve session\"));\n return;\n }\n\n LiveRequestQueue liveRequestQueue = new LiveRequestQueue();\n wsSession.getAttributes().put(LIVE_REQUEST_QUEUE_ATTR, liveRequestQueue);\n\n Runner runner;\n try {\n runner = this.runnerService.getRunner(appName);\n } catch (ResponseStatusException e) {\n log.error(\n \"Failed to get runner for app {} during WebSocket connection: {}\",\n appName,\n e.getMessage());\n wsSession.close(\n CloseStatus.SERVER_ERROR.withReason(\"Runner unavailable: \" + e.getReason()));\n return;\n }\n\n Flowable eventStream = runner.runLive(session, liveRequestQueue, runConfig);\n\n Disposable disposable =\n eventStream\n .subscribeOn(Schedulers.io()) // Offload runner work\n .observeOn(Schedulers.io()) // Send messages on I/O threads\n .subscribe(\n event -> {\n try {\n String jsonEvent = objectMapper.writeValueAsString(event);\n log.debug(\n \"Sending event via WebSocket session {}: {}\",\n wsSession.getId(),\n jsonEvent);\n wsSession.sendMessage(new TextMessage(jsonEvent));\n } catch (JsonProcessingException e) {\n log.error(\n \"Error serializing event to JSON for WebSocket session {}\",\n wsSession.getId(),\n e);\n // Decide if to close session or just log\n } catch (IOException e) {\n log.error(\n \"IOException sending message via WebSocket session {}\",\n wsSession.getId(),\n e);\n // This might mean the session is already closed or problematic\n // Consider closing/disposing here\n try {\n wsSession.close(\n CloseStatus.SERVER_ERROR.withReason(\"Error sending message\"));\n } catch (IOException ignored) {\n }\n }\n },\n error -> {\n log.error(\n \"Error in run_live stream for WebSocket session {}: {}\",\n wsSession.getId(),\n error.getMessage(),\n error);\n String reason =\n error.getMessage() != null ? error.getMessage() : \"Unknown error\";\n try {\n wsSession.close(\n new CloseStatus(\n 1011, // Internal Server Error for WebSocket\n reason.substring(\n 0, Math.min(reason.length(), WEBSOCKET_MAX_BYTES_FOR_REASON))));\n } catch (IOException ignored) {\n }\n },\n () -> {\n log.debug(\n \"run_live stream completed for WebSocket session {}\", wsSession.getId());\n try {\n wsSession.close(CloseStatus.NORMAL);\n } catch (IOException ignored) {\n }\n });\n wsSession.getAttributes().put(LIVE_SUBSCRIPTION_ATTR, disposable);\n log.debug(\"Live run started for WebSocket session {}\", wsSession.getId());\n }\n\n @Override\n protected void handleTextMessage(WebSocketSession wsSession, TextMessage message)\n throws Exception {\n LiveRequestQueue liveRequestQueue =\n (LiveRequestQueue) wsSession.getAttributes().get(LIVE_REQUEST_QUEUE_ATTR);\n\n if (liveRequestQueue == null) {\n log.warn(\n \"Received message on WebSocket session {} but LiveRequestQueue is not available (null).\"\n + \" Message: {}\",\n wsSession.getId(),\n message.getPayload());\n return;\n }\n\n try {\n String payload = message.getPayload();\n log.debug(\"Received text message on WebSocket session {}: {}\", wsSession.getId(), payload);\n\n JsonNode rootNode = objectMapper.readTree(payload);\n LiveRequest.Builder liveRequestBuilder = LiveRequest.builder();\n\n if (rootNode.has(\"content\")) {\n Content content = objectMapper.treeToValue(rootNode.get(\"content\"), Content.class);\n liveRequestBuilder.content(content);\n }\n\n if (rootNode.has(\"blob\")) {\n JsonNode blobNode = rootNode.get(\"blob\");\n Blob.Builder blobBuilder = Blob.builder();\n if (blobNode.has(\"displayName\")) {\n blobBuilder.displayName(blobNode.get(\"displayName\").asText());\n }\n if (blobNode.has(\"data\")) {\n blobBuilder.data(blobNode.get(\"data\").binaryValue());\n }\n // Handle both mime_type and mimeType. Blob states mimeType but we get mime_type from the\n // frontend.\n String mimeType =\n blobNode.has(\"mimeType\")\n ? blobNode.get(\"mimeType\").asText()\n : (blobNode.has(\"mime_type\") ? blobNode.get(\"mime_type\").asText() : null);\n if (mimeType != null) {\n blobBuilder.mimeType(mimeType);\n }\n liveRequestBuilder.blob(blobBuilder.build());\n }\n LiveRequest liveRequest = liveRequestBuilder.build();\n liveRequestQueue.send(liveRequest);\n } catch (JsonProcessingException e) {\n log.error(\n \"Error deserializing LiveRequest from WebSocket message for session {}: {}\",\n wsSession.getId(),\n message.getPayload(),\n e);\n wsSession.sendMessage(\n new TextMessage(\n \"{\\\"error\\\":\\\"Invalid JSON format for LiveRequest\\\", \\\"details\\\":\\\"\"\n + e.getMessage()\n + \"\\\"}\"));\n } catch (Exception e) {\n log.error(\n \"Unexpected error processing text message for WebSocket session {}: {}\",\n wsSession.getId(),\n message.getPayload(),\n e);\n String reason = e.getMessage() != null ? e.getMessage() : \"Error processing message\";\n wsSession.close(\n new CloseStatus(\n 1011,\n reason.substring(0, Math.min(reason.length(), WEBSOCKET_MAX_BYTES_FOR_REASON))));\n }\n }\n\n @Override\n public void handleTransportError(WebSocketSession wsSession, Throwable exception)\n throws Exception {\n log.error(\n \"WebSocket transport error for session {}: {}\",\n wsSession.getId(),\n exception.getMessage(),\n exception);\n // Cleanup resources similar to afterConnectionClosed\n cleanupSession(wsSession);\n if (wsSession.isOpen()) {\n String reason = exception.getMessage() != null ? exception.getMessage() : \"Transport error\";\n wsSession.close(\n CloseStatus.PROTOCOL_ERROR.withReason(\n reason.substring(0, Math.min(reason.length(), WEBSOCKET_MAX_BYTES_FOR_REASON))));\n }\n }\n\n @Override\n public void afterConnectionClosed(WebSocketSession wsSession, CloseStatus status)\n throws Exception {\n log.info(\n \"WebSocket connection closed: {} with status {}\", wsSession.getId(), status.toString());\n cleanupSession(wsSession);\n }\n\n private void cleanupSession(WebSocketSession wsSession) {\n LiveRequestQueue liveRequestQueue =\n (LiveRequestQueue) wsSession.getAttributes().remove(LIVE_REQUEST_QUEUE_ATTR);\n if (liveRequestQueue != null) {\n liveRequestQueue.close(); // Signal end of input to the runner\n log.debug(\"Called close() on LiveRequestQueue for session {}\", wsSession.getId());\n }\n\n Disposable disposable = (Disposable) wsSession.getAttributes().remove(LIVE_SUBSCRIPTION_ATTR);\n if (disposable != null && !disposable.isDisposed()) {\n disposable.dispose();\n }\n log.debug(\"Cleaned up resources for WebSocket session {}\", wsSession.getId());\n }\n }\n\n /**\n * Main entry point for the Spring Boot application.\n *\n * @param args Command line arguments.\n */\n public static void main(String[] args) {\n System.setProperty(\n \"org.apache.tomcat.websocket.DEFAULT_BUFFER_SIZE\", String.valueOf(10 * 1024 * 1024));\n SpringApplication.run(AdkWebServer.class, args);\n log.info(\"AdkWebServer application started successfully.\");\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/agents/LlmAgent.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.agents;\n\nimport static java.util.stream.Collectors.joining;\n\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.google.adk.SchemaUtils;\nimport com.google.adk.agents.Callbacks.AfterAgentCallback;\nimport com.google.adk.agents.Callbacks.AfterAgentCallbackBase;\nimport com.google.adk.agents.Callbacks.AfterAgentCallbackSync;\nimport com.google.adk.agents.Callbacks.AfterModelCallback;\nimport com.google.adk.agents.Callbacks.AfterModelCallbackBase;\nimport com.google.adk.agents.Callbacks.AfterModelCallbackSync;\nimport com.google.adk.agents.Callbacks.AfterToolCallback;\nimport com.google.adk.agents.Callbacks.AfterToolCallbackBase;\nimport com.google.adk.agents.Callbacks.AfterToolCallbackSync;\nimport com.google.adk.agents.Callbacks.BeforeAgentCallback;\nimport com.google.adk.agents.Callbacks.BeforeAgentCallbackBase;\nimport com.google.adk.agents.Callbacks.BeforeAgentCallbackSync;\nimport com.google.adk.agents.Callbacks.BeforeModelCallback;\nimport com.google.adk.agents.Callbacks.BeforeModelCallbackBase;\nimport com.google.adk.agents.Callbacks.BeforeModelCallbackSync;\nimport com.google.adk.agents.Callbacks.BeforeToolCallback;\nimport com.google.adk.agents.Callbacks.BeforeToolCallbackBase;\nimport com.google.adk.agents.Callbacks.BeforeToolCallbackSync;\nimport com.google.adk.events.Event;\nimport com.google.adk.examples.BaseExampleProvider;\nimport com.google.adk.examples.Example;\nimport com.google.adk.flows.llmflows.AutoFlow;\nimport com.google.adk.flows.llmflows.BaseLlmFlow;\nimport com.google.adk.flows.llmflows.SingleFlow;\nimport com.google.adk.models.BaseLlm;\nimport com.google.adk.models.Model;\nimport com.google.adk.tools.BaseTool;\nimport com.google.adk.tools.BaseToolset;\nimport com.google.common.base.Preconditions;\nimport com.google.common.collect.ImmutableList;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.GenerateContentConfig;\nimport com.google.genai.types.Schema;\nimport io.reactivex.rxjava3.core.Flowable;\nimport io.reactivex.rxjava3.core.Maybe;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.concurrent.Executor;\nimport javax.annotation.Nullable;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/** The LLM-based agent. */\npublic class LlmAgent extends BaseAgent {\n\n private static final Logger logger = LoggerFactory.getLogger(LlmAgent.class);\n\n /**\n * Enum to define if contents of previous events should be included in requests to the underlying\n * LLM.\n */\n public enum IncludeContents {\n DEFAULT,\n NONE\n }\n\n private final Optional model;\n private final Instruction instruction;\n private final Instruction globalInstruction;\n private final List toolsUnion;\n private final Optional generateContentConfig;\n private final Optional exampleProvider;\n private final IncludeContents includeContents;\n\n private final boolean planning;\n private final Optional maxSteps;\n private final boolean disallowTransferToParent;\n private final boolean disallowTransferToPeers;\n private final Optional> beforeModelCallback;\n private final Optional> afterModelCallback;\n private final Optional> beforeToolCallback;\n private final Optional> afterToolCallback;\n private final Optional inputSchema;\n private final Optional outputSchema;\n private final Optional executor;\n private final Optional outputKey;\n\n private volatile Model resolvedModel;\n private final BaseLlmFlow llmFlow;\n\n protected LlmAgent(Builder builder) {\n super(\n builder.name,\n builder.description,\n builder.subAgents,\n builder.beforeAgentCallback,\n builder.afterAgentCallback);\n this.model = Optional.ofNullable(builder.model);\n this.instruction =\n builder.instruction == null ? new Instruction.Static(\"\") : builder.instruction;\n this.globalInstruction =\n builder.globalInstruction == null ? new Instruction.Static(\"\") : builder.globalInstruction;\n this.generateContentConfig = Optional.ofNullable(builder.generateContentConfig);\n this.exampleProvider = Optional.ofNullable(builder.exampleProvider);\n this.includeContents =\n builder.includeContents != null ? builder.includeContents : IncludeContents.DEFAULT;\n this.planning = builder.planning != null && builder.planning;\n this.maxSteps = Optional.ofNullable(builder.maxSteps);\n this.disallowTransferToParent = builder.disallowTransferToParent;\n this.disallowTransferToPeers = builder.disallowTransferToPeers;\n this.beforeModelCallback = Optional.ofNullable(builder.beforeModelCallback);\n this.afterModelCallback = Optional.ofNullable(builder.afterModelCallback);\n this.beforeToolCallback = Optional.ofNullable(builder.beforeToolCallback);\n this.afterToolCallback = Optional.ofNullable(builder.afterToolCallback);\n this.inputSchema = Optional.ofNullable(builder.inputSchema);\n this.outputSchema = Optional.ofNullable(builder.outputSchema);\n this.executor = Optional.ofNullable(builder.executor);\n this.outputKey = Optional.ofNullable(builder.outputKey);\n this.toolsUnion = builder.toolsUnion != null ? builder.toolsUnion : ImmutableList.of();\n\n this.llmFlow = determineLlmFlow();\n\n // Validate name not empty.\n Preconditions.checkArgument(!this.name().isEmpty(), \"Agent name cannot be empty.\");\n }\n\n /** Returns a {@link Builder} for {@link LlmAgent}. */\n public static Builder builder() {\n return new Builder();\n }\n\n /** Builder for {@link LlmAgent}. */\n public static class Builder {\n private String name;\n private String description;\n\n private Model model;\n\n private Instruction instruction;\n private Instruction globalInstruction;\n private ImmutableList subAgents;\n private ImmutableList toolsUnion;\n private GenerateContentConfig generateContentConfig;\n private BaseExampleProvider exampleProvider;\n private IncludeContents includeContents;\n private Boolean planning;\n private Integer maxSteps;\n private Boolean disallowTransferToParent;\n private Boolean disallowTransferToPeers;\n private ImmutableList beforeModelCallback;\n private ImmutableList afterModelCallback;\n private ImmutableList beforeAgentCallback;\n private ImmutableList afterAgentCallback;\n private ImmutableList beforeToolCallback;\n private ImmutableList afterToolCallback;\n private Schema inputSchema;\n private Schema outputSchema;\n private Executor executor;\n private String outputKey;\n\n @CanIgnoreReturnValue\n public Builder name(String name) {\n this.name = name;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder description(String description) {\n this.description = description;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder model(String model) {\n this.model = Model.builder().modelName(model).build();\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder model(BaseLlm model) {\n this.model = Model.builder().model(model).build();\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder instruction(Instruction instruction) {\n this.instruction = instruction;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder instruction(String instruction) {\n this.instruction = (instruction == null) ? null : new Instruction.Static(instruction);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder globalInstruction(Instruction globalInstruction) {\n this.globalInstruction = globalInstruction;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder globalInstruction(String globalInstruction) {\n this.globalInstruction =\n (globalInstruction == null) ? null : new Instruction.Static(globalInstruction);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder subAgents(List subAgents) {\n this.subAgents = ImmutableList.copyOf(subAgents);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder subAgents(BaseAgent... subAgents) {\n this.subAgents = ImmutableList.copyOf(subAgents);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder tools(List tools) {\n this.toolsUnion = ImmutableList.copyOf(tools);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder tools(Object... tools) {\n this.toolsUnion = ImmutableList.copyOf(tools);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder generateContentConfig(GenerateContentConfig generateContentConfig) {\n this.generateContentConfig = generateContentConfig;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder exampleProvider(BaseExampleProvider exampleProvider) {\n this.exampleProvider = exampleProvider;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder exampleProvider(List examples) {\n this.exampleProvider =\n new BaseExampleProvider() {\n @Override\n public List getExamples(String query) {\n return examples;\n }\n };\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder exampleProvider(Example... examples) {\n this.exampleProvider =\n new BaseExampleProvider() {\n @Override\n public ImmutableList getExamples(String query) {\n return ImmutableList.copyOf(examples);\n }\n };\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder includeContents(IncludeContents includeContents) {\n this.includeContents = includeContents;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder planning(boolean planning) {\n this.planning = planning;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder maxSteps(int maxSteps) {\n this.maxSteps = maxSteps;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder disallowTransferToParent(boolean disallowTransferToParent) {\n this.disallowTransferToParent = disallowTransferToParent;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder disallowTransferToPeers(boolean disallowTransferToPeers) {\n this.disallowTransferToPeers = disallowTransferToPeers;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeModelCallback(BeforeModelCallback beforeModelCallback) {\n this.beforeModelCallback = ImmutableList.of(beforeModelCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeModelCallback(List beforeModelCallback) {\n if (beforeModelCallback == null) {\n this.beforeModelCallback = null;\n } else if (beforeModelCallback.isEmpty()) {\n this.beforeModelCallback = ImmutableList.of();\n } else {\n ImmutableList.Builder builder = ImmutableList.builder();\n for (BeforeModelCallbackBase callback : beforeModelCallback) {\n if (callback instanceof BeforeModelCallback beforeModelCallbackInstance) {\n builder.add(beforeModelCallbackInstance);\n } else if (callback instanceof BeforeModelCallbackSync beforeModelCallbackSyncInstance) {\n builder.add(\n (BeforeModelCallback)\n (callbackContext, llmRequest) ->\n Maybe.fromOptional(\n beforeModelCallbackSyncInstance.call(callbackContext, llmRequest)));\n } else {\n logger.warn(\n \"Invalid beforeModelCallback callback type: %s. Ignoring this callback.\",\n callback.getClass().getName());\n }\n }\n this.beforeModelCallback = builder.build();\n }\n\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeModelCallbackSync(BeforeModelCallbackSync beforeModelCallbackSync) {\n this.beforeModelCallback =\n ImmutableList.of(\n (callbackContext, llmRequest) ->\n Maybe.fromOptional(beforeModelCallbackSync.call(callbackContext, llmRequest)));\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterModelCallback(AfterModelCallback afterModelCallback) {\n this.afterModelCallback = ImmutableList.of(afterModelCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterModelCallback(List afterModelCallback) {\n if (afterModelCallback == null) {\n this.afterModelCallback = null;\n } else if (afterModelCallback.isEmpty()) {\n this.afterModelCallback = ImmutableList.of();\n } else {\n ImmutableList.Builder builder = ImmutableList.builder();\n for (AfterModelCallbackBase callback : afterModelCallback) {\n if (callback instanceof AfterModelCallback afterModelCallbackInstance) {\n builder.add(afterModelCallbackInstance);\n } else if (callback instanceof AfterModelCallbackSync afterModelCallbackSyncInstance) {\n builder.add(\n (AfterModelCallback)\n (callbackContext, llmResponse) ->\n Maybe.fromOptional(\n afterModelCallbackSyncInstance.call(callbackContext, llmResponse)));\n } else {\n logger.warn(\n \"Invalid afterModelCallback callback type: %s. Ignoring this callback.\",\n callback.getClass().getName());\n }\n }\n this.afterModelCallback = builder.build();\n }\n\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterModelCallbackSync(AfterModelCallbackSync afterModelCallbackSync) {\n this.afterModelCallback =\n ImmutableList.of(\n (callbackContext, llmResponse) ->\n Maybe.fromOptional(afterModelCallbackSync.call(callbackContext, llmResponse)));\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeAgentCallback(BeforeAgentCallback beforeAgentCallback) {\n this.beforeAgentCallback = ImmutableList.of(beforeAgentCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeAgentCallback(List beforeAgentCallback) {\n this.beforeAgentCallback = CallbackUtil.getBeforeAgentCallbacks(beforeAgentCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeAgentCallbackSync(BeforeAgentCallbackSync beforeAgentCallbackSync) {\n this.beforeAgentCallback =\n ImmutableList.of(\n (callbackContext) ->\n Maybe.fromOptional(beforeAgentCallbackSync.call(callbackContext)));\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterAgentCallback(AfterAgentCallback afterAgentCallback) {\n this.afterAgentCallback = ImmutableList.of(afterAgentCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterAgentCallback(List afterAgentCallback) {\n this.afterAgentCallback = CallbackUtil.getAfterAgentCallbacks(afterAgentCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterAgentCallbackSync(AfterAgentCallbackSync afterAgentCallbackSync) {\n this.afterAgentCallback =\n ImmutableList.of(\n (callbackContext) ->\n Maybe.fromOptional(afterAgentCallbackSync.call(callbackContext)));\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeToolCallback(BeforeToolCallback beforeToolCallback) {\n this.beforeToolCallback = ImmutableList.of(beforeToolCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeToolCallback(@Nullable List beforeToolCallbacks) {\n if (beforeToolCallbacks == null) {\n this.beforeToolCallback = null;\n } else if (beforeToolCallbacks.isEmpty()) {\n this.beforeToolCallback = ImmutableList.of();\n } else {\n ImmutableList.Builder builder = ImmutableList.builder();\n for (BeforeToolCallbackBase callback : beforeToolCallbacks) {\n if (callback instanceof BeforeToolCallback beforeToolCallbackInstance) {\n builder.add(beforeToolCallbackInstance);\n } else if (callback instanceof BeforeToolCallbackSync beforeToolCallbackSyncInstance) {\n builder.add(\n (invocationContext, baseTool, input, toolContext) ->\n Maybe.fromOptional(\n beforeToolCallbackSyncInstance.call(\n invocationContext, baseTool, input, toolContext)));\n } else {\n logger.warn(\n \"Invalid beforeToolCallback callback type: {}. Ignoring this callback.\",\n callback.getClass().getName());\n }\n }\n this.beforeToolCallback = builder.build();\n }\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeToolCallbackSync(BeforeToolCallbackSync beforeToolCallbackSync) {\n this.beforeToolCallback =\n ImmutableList.of(\n (invocationContext, baseTool, input, toolContext) ->\n Maybe.fromOptional(\n beforeToolCallbackSync.call(\n invocationContext, baseTool, input, toolContext)));\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterToolCallback(AfterToolCallback afterToolCallback) {\n this.afterToolCallback = ImmutableList.of(afterToolCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterToolCallback(@Nullable List afterToolCallbacks) {\n if (afterToolCallbacks == null) {\n this.afterToolCallback = null;\n } else if (afterToolCallbacks.isEmpty()) {\n this.afterToolCallback = ImmutableList.of();\n } else {\n ImmutableList.Builder builder = ImmutableList.builder();\n for (AfterToolCallbackBase callback : afterToolCallbacks) {\n if (callback instanceof AfterToolCallback afterToolCallbackInstance) {\n builder.add(afterToolCallbackInstance);\n } else if (callback instanceof AfterToolCallbackSync afterToolCallbackSyncInstance) {\n builder.add(\n (invocationContext, baseTool, input, toolContext, response) ->\n Maybe.fromOptional(\n afterToolCallbackSyncInstance.call(\n invocationContext, baseTool, input, toolContext, response)));\n } else {\n logger.warn(\n \"Invalid afterToolCallback callback type: {}. Ignoring this callback.\",\n callback.getClass().getName());\n }\n }\n this.afterToolCallback = builder.build();\n }\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterToolCallbackSync(AfterToolCallbackSync afterToolCallbackSync) {\n this.afterToolCallback =\n ImmutableList.of(\n (invocationContext, baseTool, input, toolContext, response) ->\n Maybe.fromOptional(\n afterToolCallbackSync.call(\n invocationContext, baseTool, input, toolContext, response)));\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder inputSchema(Schema inputSchema) {\n this.inputSchema = inputSchema;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder outputSchema(Schema outputSchema) {\n this.outputSchema = outputSchema;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder executor(Executor executor) {\n this.executor = executor;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder outputKey(String outputKey) {\n this.outputKey = outputKey;\n return this;\n }\n\n protected void validate() {\n this.disallowTransferToParent =\n this.disallowTransferToParent != null && this.disallowTransferToParent;\n this.disallowTransferToPeers =\n this.disallowTransferToPeers != null && this.disallowTransferToPeers;\n\n if (this.outputSchema != null) {\n if (!this.disallowTransferToParent || !this.disallowTransferToPeers) {\n System.err.println(\n \"Warning: Invalid config for agent \"\n + this.name\n + \": outputSchema cannot co-exist with agent transfer\"\n + \" configurations. Setting disallowTransferToParent=true and\"\n + \" disallowTransferToPeers=true.\");\n this.disallowTransferToParent = true;\n this.disallowTransferToPeers = true;\n }\n\n if (this.subAgents != null && !this.subAgents.isEmpty()) {\n throw new IllegalArgumentException(\n \"Invalid config for agent \"\n + this.name\n + \": if outputSchema is set, subAgents must be empty to disable agent\"\n + \" transfer.\");\n }\n if (this.toolsUnion != null && !this.toolsUnion.isEmpty()) {\n throw new IllegalArgumentException(\n \"Invalid config for agent \"\n + this.name\n + \": if outputSchema is set, tools must be empty.\");\n }\n }\n }\n\n public LlmAgent build() {\n validate();\n return new LlmAgent(this);\n }\n }\n\n protected BaseLlmFlow determineLlmFlow() {\n if (disallowTransferToParent() && disallowTransferToPeers() && subAgents().isEmpty()) {\n return new SingleFlow(maxSteps);\n } else {\n return new AutoFlow(maxSteps);\n }\n }\n\n private void maybeSaveOutputToState(Event event) {\n if (outputKey().isPresent() && event.finalResponse() && event.content().isPresent()) {\n // Concatenate text from all parts.\n Object output;\n String rawResult =\n event.content().flatMap(Content::parts).orElse(ImmutableList.of()).stream()\n .map(part -> part.text().orElse(\"\"))\n .collect(joining());\n\n Optional outputSchema = outputSchema();\n if (outputSchema.isPresent()) {\n try {\n Map validatedMap =\n SchemaUtils.validateOutputSchema(rawResult, outputSchema.get());\n output = validatedMap;\n } catch (JsonProcessingException e) {\n System.err.println(\n \"Error: LlmAgent output for outputKey '\"\n + outputKey().get()\n + \"' was not valid JSON, despite an outputSchema being present.\"\n + \" Saving raw output to state. Error: \"\n + e.getMessage());\n output = rawResult;\n } catch (IllegalArgumentException e) {\n System.err.println(\n \"Error: LlmAgent output for outputKey '\"\n + outputKey().get()\n + \"' did not match the outputSchema.\"\n + \" Saving raw output to state. Error: \"\n + e.getMessage());\n output = rawResult;\n }\n } else {\n output = rawResult;\n }\n event.actions().stateDelta().put(outputKey().get(), output);\n }\n }\n\n @Override\n protected Flowable runAsyncImpl(InvocationContext invocationContext) {\n return llmFlow.run(invocationContext).doOnNext(this::maybeSaveOutputToState);\n }\n\n @Override\n protected Flowable runLiveImpl(InvocationContext invocationContext) {\n return llmFlow.runLive(invocationContext).doOnNext(this::maybeSaveOutputToState);\n }\n\n /**\n * Constructs the text instruction for this agent based on the {@link #instruction} field.\n *\n *

This method is only for use by Agent Development Kit.\n *\n * @param context The context to retrieve the session state.\n * @return The resolved instruction as a {@link Single} wrapped string.\n */\n public Single canonicalInstruction(ReadonlyContext context) {\n if (instruction instanceof Instruction.Static staticInstr) {\n return Single.just(staticInstr.instruction());\n } else if (instruction instanceof Instruction.Provider provider) {\n return provider.getInstruction().apply(context);\n }\n throw new IllegalStateException(\"Unknown Instruction subtype: \" + instruction.getClass());\n }\n\n /**\n * Constructs the text global instruction for this agent based on the {@link #globalInstruction}\n * field.\n *\n *

This method is only for use by Agent Development Kit.\n *\n * @param context The context to retrieve the session state.\n * @return The resolved global instruction as a {@link Single} wrapped string.\n */\n public Single canonicalGlobalInstruction(ReadonlyContext context) {\n if (globalInstruction instanceof Instruction.Static staticInstr) {\n return Single.just(staticInstr.instruction());\n } else if (globalInstruction instanceof Instruction.Provider provider) {\n return provider.getInstruction().apply(context);\n }\n throw new IllegalStateException(\"Unknown Instruction subtype: \" + instruction.getClass());\n }\n\n /**\n * Constructs the list of tools for this agent based on the {@link #tools} field.\n *\n *

This method is only for use by Agent Development Kit.\n *\n * @param context The context to retrieve the session state.\n * @return The resolved list of tools as a {@link Single} wrapped list of {@link BaseTool}.\n */\n public Flowable canonicalTools(Optional context) {\n List> toolFlowables = new ArrayList<>();\n for (Object toolOrToolset : toolsUnion) {\n if (toolOrToolset instanceof BaseTool baseTool) {\n toolFlowables.add(Flowable.just(baseTool));\n } else if (toolOrToolset instanceof BaseToolset baseToolset) {\n toolFlowables.add(baseToolset.getTools(context.orElse(null)));\n } else {\n throw new IllegalArgumentException(\n \"Object in tools list is not of a supported type: \"\n + toolOrToolset.getClass().getName());\n }\n }\n return Flowable.concat(toolFlowables);\n }\n\n /** Overload of canonicalTools that defaults to an empty context. */\n public Flowable canonicalTools() {\n return canonicalTools(Optional.empty());\n }\n\n /** Convenience overload of canonicalTools that accepts a non-optional ReadonlyContext. */\n public Flowable canonicalTools(ReadonlyContext context) {\n return canonicalTools(Optional.ofNullable(context));\n }\n\n public Instruction instruction() {\n return instruction;\n }\n\n public Instruction globalInstruction() {\n return globalInstruction;\n }\n\n public Optional model() {\n return model;\n }\n\n public boolean planning() {\n return planning;\n }\n\n public Optional maxSteps() {\n return maxSteps;\n }\n\n public Optional generateContentConfig() {\n return generateContentConfig;\n }\n\n public Optional exampleProvider() {\n return exampleProvider;\n }\n\n public IncludeContents includeContents() {\n return includeContents;\n }\n\n public List tools() {\n return canonicalTools().toList().blockingGet();\n }\n\n public List toolsUnion() {\n return toolsUnion;\n }\n\n public boolean disallowTransferToParent() {\n return disallowTransferToParent;\n }\n\n public boolean disallowTransferToPeers() {\n return disallowTransferToPeers;\n }\n\n public Optional> beforeModelCallback() {\n return beforeModelCallback;\n }\n\n public Optional> afterModelCallback() {\n return afterModelCallback;\n }\n\n public Optional> beforeToolCallback() {\n return beforeToolCallback;\n }\n\n public Optional> afterToolCallback() {\n return afterToolCallback;\n }\n\n public Optional inputSchema() {\n return inputSchema;\n }\n\n public Optional outputSchema() {\n return outputSchema;\n }\n\n public Optional executor() {\n return executor;\n }\n\n public Optional outputKey() {\n return outputKey;\n }\n\n public Model resolvedModel() {\n if (resolvedModel == null) {\n synchronized (this) {\n if (resolvedModel == null) {\n resolvedModel = resolveModelInternal();\n }\n }\n }\n return resolvedModel;\n }\n\n /**\n * Resolves the model for this agent, checking first if it is defined locally, then searching\n * through ancestors.\n *\n *

This method is only for use by Agent Development Kit.\n *\n * @return The resolved {@link Model} for this agent.\n * @throws IllegalStateException if no model is found for this agent or its ancestors.\n */\n private Model resolveModelInternal() {\n if (this.model.isPresent()) {\n if (this.model().isPresent()) {\n return this.model.get();\n }\n }\n BaseAgent current = this.parentAgent();\n while (current != null) {\n if (current instanceof LlmAgent) {\n return ((LlmAgent) current).resolvedModel();\n }\n current = current.parentAgent();\n }\n throw new IllegalStateException(\"No model found for agent \" + name() + \" or its ancestors.\");\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/sessions/ApiClient.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.StandardSystemProperty.JAVA_VERSION;\n\nimport com.google.auth.oauth2.GoogleCredentials;\nimport com.google.common.base.Ascii;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.genai.errors.GenAiIOException;\nimport com.google.genai.types.HttpOptions;\nimport java.io.IOException;\nimport java.time.Duration;\nimport java.util.Map;\nimport java.util.Optional;\nimport okhttp3.OkHttpClient;\nimport org.jspecify.annotations.Nullable;\n\n/** Interface for an API client which issues HTTP requests to the GenAI APIs. */\nabstract class ApiClient {\n OkHttpClient httpClient;\n // For Google AI APIs\n final Optional apiKey;\n // For Vertex AI APIs\n final Optional project;\n final Optional location;\n final Optional credentials;\n HttpOptions httpOptions;\n final boolean vertexAI;\n\n /** Constructs an ApiClient for Google AI APIs. */\n ApiClient(Optional apiKey, Optional customHttpOptions) {\n checkNotNull(apiKey, \"API Key cannot be null\");\n checkNotNull(customHttpOptions, \"customHttpOptions cannot be null\");\n\n try {\n this.apiKey = Optional.of(apiKey.orElse(System.getenv(\"GOOGLE_API_KEY\")));\n } catch (NullPointerException e) {\n throw new IllegalArgumentException(\n \"API key must either be provided or set in the environment variable\" + \" GOOGLE_API_KEY.\",\n e);\n }\n\n this.project = Optional.empty();\n this.location = Optional.empty();\n this.credentials = Optional.empty();\n this.vertexAI = false;\n\n this.httpOptions = defaultHttpOptions(/* vertexAI= */ false, this.location);\n\n if (customHttpOptions.isPresent()) {\n applyHttpOptions(customHttpOptions.get());\n }\n\n this.httpClient = createHttpClient(httpOptions.timeout());\n }\n\n ApiClient(\n Optional project,\n Optional location,\n Optional credentials,\n Optional customHttpOptions) {\n checkNotNull(project, \"project cannot be null\");\n checkNotNull(location, \"location cannot be null\");\n checkNotNull(credentials, \"credentials cannot be null\");\n checkNotNull(customHttpOptions, \"customHttpOptions cannot be null\");\n\n try {\n this.project = Optional.of(project.orElse(System.getenv(\"GOOGLE_CLOUD_PROJECT\")));\n } catch (NullPointerException e) {\n throw new IllegalArgumentException(\n \"Project must either be provided or set in the environment variable\"\n + \" GOOGLE_CLOUD_PROJECT.\",\n e);\n }\n if (this.project.get().isEmpty()) {\n throw new IllegalArgumentException(\"Project must not be empty.\");\n }\n\n try {\n this.location = Optional.of(location.orElse(System.getenv(\"GOOGLE_CLOUD_LOCATION\")));\n } catch (NullPointerException e) {\n throw new IllegalArgumentException(\n \"Location must either be provided or set in the environment variable\"\n + \" GOOGLE_CLOUD_LOCATION.\",\n e);\n }\n if (this.location.get().isEmpty()) {\n throw new IllegalArgumentException(\"Location must not be empty.\");\n }\n\n this.credentials = Optional.of(credentials.orElseGet(this::defaultCredentials));\n\n this.httpOptions = defaultHttpOptions(/* vertexAI= */ true, this.location);\n\n if (customHttpOptions.isPresent()) {\n applyHttpOptions(customHttpOptions.get());\n }\n this.apiKey = Optional.empty();\n this.vertexAI = true;\n this.httpClient = createHttpClient(httpOptions.timeout());\n }\n\n private OkHttpClient createHttpClient(Optional timeout) {\n OkHttpClient.Builder builder = new OkHttpClient().newBuilder();\n if (timeout.isPresent()) {\n builder.connectTimeout(Duration.ofMillis(timeout.get()));\n }\n return builder.build();\n }\n\n /** Sends a Http request given the http method, path, and request json string. */\n public abstract ApiResponse request(String httpMethod, String path, String requestJson);\n\n /** Returns the library version. */\n static String libraryVersion() {\n // TODO: Automate revisions to the SDK library version.\n String libraryLabel = \"google-genai-sdk/0.1.0\";\n String languageLabel = \"gl-java/\" + JAVA_VERSION.value();\n return libraryLabel + \" \" + languageLabel;\n }\n\n /** Returns whether the client is using Vertex AI APIs. */\n public boolean vertexAI() {\n return vertexAI;\n }\n\n /** Returns the project ID for Vertex AI APIs. */\n public @Nullable String project() {\n return project.orElse(null);\n }\n\n /** Returns the location for Vertex AI APIs. */\n public @Nullable String location() {\n return location.orElse(null);\n }\n\n /** Returns the API key for Google AI APIs. */\n public @Nullable String apiKey() {\n return apiKey.orElse(null);\n }\n\n /** Returns the HttpClient for API calls. */\n OkHttpClient httpClient() {\n return httpClient;\n }\n\n private Optional> getTimeoutHeader(HttpOptions httpOptionsToApply) {\n if (httpOptionsToApply.timeout().isPresent()) {\n int timeoutInSeconds = (int) Math.ceil((double) httpOptionsToApply.timeout().get() / 1000.0);\n // TODO(b/329147724): Document the usage of X-Server-Timeout header.\n return Optional.of(ImmutableMap.of(\"X-Server-Timeout\", Integer.toString(timeoutInSeconds)));\n }\n return Optional.empty();\n }\n\n private void applyHttpOptions(HttpOptions httpOptionsToApply) {\n HttpOptions.Builder mergedHttpOptionsBuilder = this.httpOptions.toBuilder();\n if (httpOptionsToApply.baseUrl().isPresent()) {\n mergedHttpOptionsBuilder.baseUrl(httpOptionsToApply.baseUrl().get());\n }\n if (httpOptionsToApply.apiVersion().isPresent()) {\n mergedHttpOptionsBuilder.apiVersion(httpOptionsToApply.apiVersion().get());\n }\n if (httpOptionsToApply.timeout().isPresent()) {\n mergedHttpOptionsBuilder.timeout(httpOptionsToApply.timeout().get());\n }\n if (httpOptionsToApply.headers().isPresent()) {\n ImmutableMap mergedHeaders =\n ImmutableMap.builder()\n .putAll(httpOptionsToApply.headers().orElse(ImmutableMap.of()))\n .putAll(this.httpOptions.headers().orElse(ImmutableMap.of()))\n .putAll(getTimeoutHeader(httpOptionsToApply).orElse(ImmutableMap.of()))\n .buildOrThrow();\n mergedHttpOptionsBuilder.headers(mergedHeaders);\n }\n this.httpOptions = mergedHttpOptionsBuilder.build();\n }\n\n static HttpOptions defaultHttpOptions(boolean vertexAI, Optional location) {\n ImmutableMap.Builder defaultHeaders = ImmutableMap.builder();\n defaultHeaders\n .put(\"Content-Type\", \"application/json\")\n .put(\"user-agent\", libraryVersion())\n .put(\"x-goog-api-client\", libraryVersion());\n\n HttpOptions.Builder defaultHttpOptionsBuilder =\n HttpOptions.builder().headers(defaultHeaders.buildOrThrow());\n\n if (vertexAI && location.isPresent()) {\n defaultHttpOptionsBuilder\n .baseUrl(\n Ascii.equalsIgnoreCase(location.get(), \"global\")\n ? \"https://aiplatform.googleapis.com\"\n : String.format(\"https://%s-aiplatform.googleapis.com\", location.get()))\n .apiVersion(\"v1beta1\");\n } else if (vertexAI && location.isEmpty()) {\n throw new IllegalArgumentException(\"Location must be provided for Vertex AI APIs.\");\n } else {\n defaultHttpOptionsBuilder\n .baseUrl(\"https://generativelanguage.googleapis.com\")\n .apiVersion(\"v1beta\");\n }\n return defaultHttpOptionsBuilder.build();\n }\n\n GoogleCredentials defaultCredentials() {\n try {\n return GoogleCredentials.getApplicationDefault()\n .createScoped(\"https://www.googleapis.com/auth/cloud-platform\");\n } catch (IOException e) {\n throw new GenAiIOException(\n \"Failed to get application default credentials, please explicitly provide credentials.\",\n e);\n }\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/BaseTool.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools;\n\nimport static com.google.common.collect.ImmutableList.toImmutableList;\n\nimport com.google.adk.models.LlmRequest;\nimport com.google.common.collect.ImmutableList;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport com.google.genai.types.FunctionDeclaration;\nimport com.google.genai.types.GenerateContentConfig;\nimport com.google.genai.types.Tool;\nimport io.reactivex.rxjava3.core.Completable;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.Map;\nimport java.util.Optional;\nimport javax.annotation.Nonnull;\nimport org.jspecify.annotations.Nullable;\n\n/** The base class for all ADK tools. */\npublic abstract class BaseTool {\n private final String name;\n private final String description;\n private final boolean isLongRunning;\n\n protected BaseTool(@Nonnull String name, @Nonnull String description) {\n this(name, description, /* isLongRunning= */ false);\n }\n\n protected BaseTool(@Nonnull String name, @Nonnull String description, boolean isLongRunning) {\n this.name = name;\n this.description = description;\n this.isLongRunning = isLongRunning;\n }\n\n public String name() {\n return name;\n }\n\n public String description() {\n return description;\n }\n\n public boolean longRunning() {\n return isLongRunning;\n }\n\n /** Gets the {@link FunctionDeclaration} representation of this tool. */\n public Optional declaration() {\n return Optional.empty();\n }\n\n /** Calls a tool. */\n public Single> runAsync(Map args, ToolContext toolContext) {\n throw new UnsupportedOperationException(\"This method is not implemented.\");\n }\n\n /**\n * Processes the outgoing {@link LlmRequest.Builder}.\n *\n *

This implementation adds the current tool's {@link #declaration()} to the {@link\n * GenerateContentConfig} within the builder. If a tool with function declarations already exists,\n * the current tool's declaration is merged into it. Otherwise, a new tool definition with the\n * current tool's declaration is created. The current tool itself is also added to the builder's\n * internal list of tools. Override this method for processing the outgoing request.\n */\n @CanIgnoreReturnValue\n public Completable processLlmRequest(\n LlmRequest.Builder llmRequestBuilder, ToolContext toolContext) {\n if (declaration().isEmpty()) {\n return Completable.complete();\n }\n\n llmRequestBuilder.appendTools(ImmutableList.of(this));\n\n LlmRequest llmRequest = llmRequestBuilder.build();\n ImmutableList toolsWithoutFunctionDeclarations =\n findToolsWithoutFunctionDeclarations(llmRequest);\n Tool toolWithFunctionDeclarations = findToolWithFunctionDeclarations(llmRequest);\n // If LlmRequest GenerateContentConfig already has a function calling tool,\n // merge the function declarations.\n // Otherwise, add a new tool definition with function calling declaration..\n if (toolWithFunctionDeclarations == null) {\n toolWithFunctionDeclarations =\n Tool.builder().functionDeclarations(ImmutableList.of(declaration().get())).build();\n } else {\n toolWithFunctionDeclarations =\n toolWithFunctionDeclarations.toBuilder()\n .functionDeclarations(\n ImmutableList.builder()\n .addAll(\n toolWithFunctionDeclarations\n .functionDeclarations()\n .orElse(ImmutableList.of()))\n .add(declaration().get())\n .build())\n .build();\n }\n // Patch the GenerateContentConfig with the new tool definition.\n GenerateContentConfig generateContentConfig =\n llmRequest\n .config()\n .map(GenerateContentConfig::toBuilder)\n .orElse(GenerateContentConfig.builder())\n .tools(\n new ImmutableList.Builder()\n .addAll(toolsWithoutFunctionDeclarations)\n .add(toolWithFunctionDeclarations)\n .build())\n .build();\n llmRequestBuilder.config(generateContentConfig);\n return Completable.complete();\n }\n\n /**\n * Finds a tool in GenerateContentConfig that has function calling declarations, or returns null\n * otherwise.\n */\n private static @Nullable Tool findToolWithFunctionDeclarations(LlmRequest llmRequest) {\n return llmRequest\n .config()\n .flatMap(config -> config.tools())\n .flatMap(\n tools -> tools.stream().filter(t -> t.functionDeclarations().isPresent()).findFirst())\n .orElse(null);\n }\n\n /** Finds all tools in GenerateContentConfig that do not have function calling declarations. */\n private static ImmutableList findToolsWithoutFunctionDeclarations(LlmRequest llmRequest) {\n return llmRequest\n .config()\n .flatMap(config -> config.tools())\n .map(\n tools ->\n tools.stream()\n .filter(t -> t.functionDeclarations().isEmpty())\n .collect(toImmutableList()))\n .orElse(ImmutableList.of());\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/runner/Runner.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.runner;\n\nimport com.google.adk.Telemetry;\nimport com.google.adk.agents.BaseAgent;\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.agents.LiveRequestQueue;\nimport com.google.adk.agents.LlmAgent;\nimport com.google.adk.agents.RunConfig;\nimport com.google.adk.artifacts.BaseArtifactService;\nimport com.google.adk.events.Event;\nimport com.google.adk.sessions.BaseSessionService;\nimport com.google.adk.sessions.Session;\nimport com.google.adk.utils.CollectionUtils;\nimport com.google.common.collect.ImmutableList;\nimport com.google.genai.types.AudioTranscriptionConfig;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.Modality;\nimport com.google.genai.types.Part;\nimport io.opentelemetry.api.trace.Span;\nimport io.opentelemetry.api.trace.StatusCode;\nimport io.opentelemetry.context.Scope;\nimport io.reactivex.rxjava3.core.Flowable;\nimport io.reactivex.rxjava3.core.Maybe;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Optional;\n\n/** The main class for the GenAI Agents runner. */\npublic class Runner {\n private final BaseAgent agent;\n private final String appName;\n private final BaseArtifactService artifactService;\n private final BaseSessionService sessionService;\n\n /** Creates a new {@code Runner}. */\n public Runner(\n BaseAgent agent,\n String appName,\n BaseArtifactService artifactService,\n BaseSessionService sessionService) {\n this.agent = agent;\n this.appName = appName;\n this.artifactService = artifactService;\n this.sessionService = sessionService;\n }\n\n public BaseAgent agent() {\n return this.agent;\n }\n\n public String appName() {\n return this.appName;\n }\n\n public BaseArtifactService artifactService() {\n return this.artifactService;\n }\n\n public BaseSessionService sessionService() {\n return this.sessionService;\n }\n\n /**\n * Appends a new user message to the session history.\n *\n * @throws IllegalArgumentException if message has no parts.\n */\n private void appendNewMessageToSession(\n Session session,\n Content newMessage,\n InvocationContext invocationContext,\n boolean saveInputBlobsAsArtifacts) {\n if (newMessage.parts().isEmpty()) {\n throw new IllegalArgumentException(\"No parts in the new_message.\");\n }\n\n if (this.artifactService != null && saveInputBlobsAsArtifacts) {\n // The runner directly saves the artifacts (if applicable) in the\n // user message and replaces the artifact data with a file name\n // placeholder.\n for (int i = 0; i < newMessage.parts().get().size(); i++) {\n Part part = newMessage.parts().get().get(i);\n if (part.inlineData().isEmpty()) {\n continue;\n }\n String fileName = \"artifact_\" + invocationContext.invocationId() + \"_\" + i;\n var unused =\n this.artifactService.saveArtifact(\n this.appName, session.userId(), session.id(), fileName, part);\n\n newMessage\n .parts()\n .get()\n .set(\n i,\n Part.fromText(\n \"Uploaded file: \" + fileName + \". It has been saved to the artifacts\"));\n }\n }\n // Appends only. We do not yield the event because it's not from the model.\n Event event =\n Event.builder()\n .id(Event.generateEventId())\n .invocationId(invocationContext.invocationId())\n .author(\"user\")\n .content(Optional.of(newMessage))\n .build();\n this.sessionService.appendEvent(session, event);\n }\n\n /**\n * Runs the agent in the standard mode.\n *\n * @param userId The ID of the user for the session.\n * @param sessionId The ID of the session to run the agent in.\n * @param newMessage The new message from the user to process.\n * @param runConfig Configuration for the agent run.\n * @return A Flowable stream of {@link Event} objects generated by the agent during execution.\n */\n public Flowable runAsync(\n String userId, String sessionId, Content newMessage, RunConfig runConfig) {\n Maybe maybeSession =\n this.sessionService.getSession(appName, userId, sessionId, Optional.empty());\n return maybeSession\n .switchIfEmpty(\n Single.error(\n new IllegalArgumentException(\n String.format(\"Session not found: %s for user %s\", sessionId, userId))))\n .flatMapPublisher(session -> this.runAsync(session, newMessage, runConfig));\n }\n\n /**\n * Asynchronously runs the agent for a given user and session, processing a new message and using\n * a default {@link RunConfig}.\n *\n *

This method initiates an agent execution within the specified session, appending the\n * provided new message to the session's history. It utilizes a default {@code RunConfig} to\n * control execution parameters. The method returns a stream of {@link Event} objects representing\n * the agent's activity during the run.\n *\n * @param userId The ID of the user initiating the session.\n * @param sessionId The ID of the session in which the agent will run.\n * @param newMessage The new {@link Content} message to be processed by the agent.\n * @return A {@link Flowable} emitting {@link Event} objects generated by the agent.\n */\n public Flowable runAsync(String userId, String sessionId, Content newMessage) {\n return runAsync(userId, sessionId, newMessage, RunConfig.builder().build());\n }\n\n /**\n * Runs the agent in the standard mode using a provided Session object.\n *\n * @param session The session to run the agent in.\n * @param newMessage The new message from the user to process.\n * @param runConfig Configuration for the agent run.\n * @return A Flowable stream of {@link Event} objects generated by the agent during execution.\n */\n public Flowable runAsync(Session session, Content newMessage, RunConfig runConfig) {\n Span span = Telemetry.getTracer().spanBuilder(\"invocation\").startSpan();\n try (Scope scope = span.makeCurrent()) {\n return Flowable.just(session)\n .flatMap(\n sess -> {\n BaseAgent rootAgent = this.agent;\n InvocationContext invocationContext =\n InvocationContext.create(\n this.sessionService,\n this.artifactService,\n InvocationContext.newInvocationContextId(),\n rootAgent,\n sess,\n newMessage,\n runConfig);\n\n if (newMessage != null) {\n appendNewMessageToSession(\n sess, newMessage, invocationContext, runConfig.saveInputBlobsAsArtifacts());\n }\n\n invocationContext.agent(this.findAgentToRun(sess, rootAgent));\n Flowable events = invocationContext.agent().runAsync(invocationContext);\n return events.doOnNext(event -> this.sessionService.appendEvent(sess, event));\n })\n .doOnError(\n throwable -> {\n span.setStatus(StatusCode.ERROR, \"Error in runAsync Flowable execution\");\n span.recordException(throwable);\n })\n .doFinally(span::end);\n } catch (Throwable t) {\n span.setStatus(StatusCode.ERROR, \"Error during runAsync synchronous setup\");\n span.recordException(t);\n span.end();\n return Flowable.error(t);\n }\n }\n\n /**\n * Creates an {@link InvocationContext} for a live (streaming) run.\n *\n * @return invocation context configured for a live run.\n */\n private InvocationContext newInvocationContextForLive(\n Session session, Optional liveRequestQueue, RunConfig runConfig) {\n RunConfig.Builder runConfigBuilder = RunConfig.builder(runConfig);\n if (!CollectionUtils.isNullOrEmpty(runConfig.responseModalities())\n && liveRequestQueue.isPresent()) {\n // Default to AUDIO modality if not specified.\n if (CollectionUtils.isNullOrEmpty(runConfig.responseModalities())) {\n runConfigBuilder.setResponseModalities(\n ImmutableList.of(new Modality(Modality.Known.AUDIO)));\n if (runConfig.outputAudioTranscription() == null) {\n runConfigBuilder.setOutputAudioTranscription(AudioTranscriptionConfig.builder().build());\n }\n } else if (!runConfig.responseModalities().contains(new Modality(Modality.Known.TEXT))) {\n if (runConfig.outputAudioTranscription() == null) {\n runConfigBuilder.setOutputAudioTranscription(AudioTranscriptionConfig.builder().build());\n }\n }\n }\n return newInvocationContext(session, liveRequestQueue, runConfigBuilder.build());\n }\n\n /**\n * Creates an {@link InvocationContext} for the given session, request queue, and config.\n *\n * @return a new {@link InvocationContext}.\n */\n private InvocationContext newInvocationContext(\n Session session, Optional liveRequestQueue, RunConfig runConfig) {\n BaseAgent rootAgent = this.agent;\n InvocationContext invocationContext =\n InvocationContext.create(\n this.sessionService,\n this.artifactService,\n rootAgent,\n session,\n liveRequestQueue.orElse(null),\n runConfig);\n invocationContext.agent(this.findAgentToRun(session, rootAgent));\n return invocationContext;\n }\n\n /**\n * Runs the agent in live mode, appending generated events to the session.\n *\n * @return stream of events from the agent.\n */\n public Flowable runLive(\n Session session, LiveRequestQueue liveRequestQueue, RunConfig runConfig) {\n Span span = Telemetry.getTracer().spanBuilder(\"invocation\").startSpan();\n try (Scope scope = span.makeCurrent()) {\n InvocationContext invocationContext =\n newInvocationContextForLive(session, Optional.of(liveRequestQueue), runConfig);\n return invocationContext\n .agent()\n .runLive(invocationContext)\n .doOnNext(event -> this.sessionService.appendEvent(session, event))\n .doOnError(\n throwable -> {\n span.setStatus(StatusCode.ERROR, \"Error in runLive Flowable execution\");\n span.recordException(throwable);\n })\n .doFinally(span::end);\n } catch (Throwable t) {\n span.setStatus(StatusCode.ERROR, \"Error during runLive synchronous setup\");\n span.recordException(t);\n span.end();\n return Flowable.error(t);\n }\n }\n\n /**\n * Retrieves the session and runs the agent in live mode.\n *\n * @return stream of events from the agent.\n * @throws IllegalArgumentException if the session is not found.\n */\n public Flowable runLive(\n String userId, String sessionId, LiveRequestQueue liveRequestQueue, RunConfig runConfig) {\n return this.sessionService\n .getSession(appName, userId, sessionId, Optional.empty())\n .flatMapPublisher(\n session -> {\n if (session == null) {\n return Flowable.error(\n new IllegalArgumentException(\n String.format(\"Session not found: %s for user %s\", sessionId, userId)));\n }\n return this.runLive(session, liveRequestQueue, runConfig);\n });\n }\n\n /**\n * Runs the agent asynchronously with a default user ID.\n *\n * @return stream of generated events.\n */\n public Flowable runWithSessionId(\n String sessionId, Content newMessage, RunConfig runConfig) {\n // TODO(b/410859954): Add user_id to getter or method signature. Assuming \"tmp-user\" for now.\n return this.runAsync(\"tmp-user\", sessionId, newMessage, runConfig);\n }\n\n /**\n * Checks if the agent and its parent chain allow transfer up the tree.\n *\n * @return true if transferable, false otherwise.\n */\n private boolean isTransferableAcrossAgentTree(BaseAgent agentToRun) {\n BaseAgent current = agentToRun;\n while (current != null) {\n // Agents eligible to transfer must have an LLM-based agent parent.\n if (!(current instanceof LlmAgent)) {\n return false;\n }\n // If any agent can't transfer to its parent, the chain is broken.\n LlmAgent agent = (LlmAgent) current;\n if (agent.disallowTransferToParent()) {\n return false;\n }\n current = current.parentAgent();\n }\n return true;\n }\n\n /**\n * Returns the agent that should handle the next request based on session history.\n *\n * @return agent to run.\n */\n private BaseAgent findAgentToRun(Session session, BaseAgent rootAgent) {\n List events = new ArrayList<>(session.events());\n Collections.reverse(events);\n\n for (Event event : events) {\n String author = event.author();\n if (author.equals(\"user\")) {\n continue;\n }\n\n if (author.equals(rootAgent.name())) {\n return rootAgent;\n }\n\n BaseAgent agent = rootAgent.findSubAgent(author);\n\n if (agent == null) {\n continue;\n }\n\n if (this.isTransferableAcrossAgentTree(agent)) {\n return agent;\n }\n }\n\n return rootAgent;\n }\n\n // TODO: run statelessly\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/models/LlmResponse.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.models;\n\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.databind.annotation.JsonDeserialize;\nimport com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;\nimport com.google.adk.JsonBaseModel;\nimport com.google.auto.value.AutoValue;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport com.google.genai.types.Candidate;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.FinishReason;\nimport com.google.genai.types.GenerateContentResponse;\nimport com.google.genai.types.GenerateContentResponsePromptFeedback;\nimport com.google.genai.types.GroundingMetadata;\nimport java.util.List;\nimport java.util.Optional;\nimport javax.annotation.Nullable;\n\n/** Represents a response received from the LLM. */\n@AutoValue\n@JsonDeserialize(builder = LlmResponse.Builder.class)\npublic abstract class LlmResponse extends JsonBaseModel {\n\n LlmResponse() {}\n\n /**\n * Returns the content of the first candidate in the response, if available.\n *\n * @return An {@link Content} of the first {@link Candidate} in the {@link\n * GenerateContentResponse} if the response contains at least one candidate., or an empty\n * optional if no candidates are present in the response.\n */\n @JsonProperty(\"content\")\n public abstract Optional content();\n\n /**\n * Returns the grounding metadata of the first candidate in the response, if available.\n *\n * @return An {@link Optional} containing {@link GroundingMetadata} or empty.\n */\n @JsonProperty(\"groundingMetadata\")\n public abstract Optional groundingMetadata();\n\n /**\n * Indicates whether the text content is part of a unfinished text stream.\n *\n *

Only used for streaming mode and when the content is plain text.\n */\n @JsonProperty(\"partial\")\n public abstract Optional partial();\n\n /**\n * Indicates whether the response from the model is complete.\n *\n *

Only used for streaming mode.\n */\n @JsonProperty(\"turnComplete\")\n public abstract Optional turnComplete();\n\n /** Error code if the response is an error. Code varies by model. */\n @JsonProperty(\"errorCode\")\n public abstract Optional errorCode();\n\n /** Error message if the response is an error. */\n @JsonProperty(\"errorMessage\")\n public abstract Optional errorMessage();\n\n /**\n * Indicates that LLM was interrupted when generating the content. Usually it's due to user\n * interruption during a bidi streaming.\n */\n @JsonProperty(\"interrupted\")\n public abstract Optional interrupted();\n\n public abstract Builder toBuilder();\n\n /** Builder for constructing {@link LlmResponse} instances. */\n @AutoValue.Builder\n @JsonPOJOBuilder(buildMethodName = \"build\", withPrefix = \"\")\n public abstract static class Builder {\n\n @JsonCreator\n static LlmResponse.Builder jacksonBuilder() {\n return LlmResponse.builder();\n }\n\n @JsonProperty(\"content\")\n public abstract Builder content(Content content);\n\n @JsonProperty(\"interrupted\")\n public abstract Builder interrupted(@Nullable Boolean interrupted);\n\n public abstract Builder interrupted(Optional interrupted);\n\n @JsonProperty(\"groundingMetadata\")\n public abstract Builder groundingMetadata(@Nullable GroundingMetadata groundingMetadata);\n\n public abstract Builder groundingMetadata(Optional groundingMetadata);\n\n @JsonProperty(\"partial\")\n public abstract Builder partial(@Nullable Boolean partial);\n\n public abstract Builder partial(Optional partial);\n\n @JsonProperty(\"turnComplete\")\n public abstract Builder turnComplete(@Nullable Boolean turnComplete);\n\n public abstract Builder turnComplete(Optional turnComplete);\n\n @JsonProperty(\"errorCode\")\n public abstract Builder errorCode(@Nullable FinishReason errorCode);\n\n public abstract Builder errorCode(Optional errorCode);\n\n @JsonProperty(\"errorMessage\")\n public abstract Builder errorMessage(@Nullable String errorMessage);\n\n public abstract Builder errorMessage(Optional errorMessage);\n\n @CanIgnoreReturnValue\n public final Builder response(GenerateContentResponse response) {\n Optional> candidatesOpt = response.candidates();\n if (candidatesOpt.isPresent() && !candidatesOpt.get().isEmpty()) {\n Candidate candidate = candidatesOpt.get().get(0);\n if (candidate.content().isPresent()) {\n this.content(candidate.content().get());\n this.groundingMetadata(candidate.groundingMetadata());\n } else {\n candidate.finishReason().ifPresent(this::errorCode);\n candidate.finishMessage().ifPresent(this::errorMessage);\n }\n } else {\n Optional promptFeedbackOpt =\n response.promptFeedback();\n if (promptFeedbackOpt.isPresent()) {\n GenerateContentResponsePromptFeedback promptFeedback = promptFeedbackOpt.get();\n promptFeedback\n .blockReason()\n .ifPresent(reason -> this.errorCode(new FinishReason(reason.toString())));\n promptFeedback.blockReasonMessage().ifPresent(this::errorMessage);\n } else {\n this.errorCode(new FinishReason(\"Unknown error.\"));\n this.errorMessage(\"Unknown error.\");\n }\n }\n return this;\n }\n\n abstract LlmResponse autoBuild();\n\n public LlmResponse build() {\n return autoBuild();\n }\n }\n\n public static Builder builder() {\n return new AutoValue_LlmResponse.Builder();\n }\n\n public static LlmResponse create(List candidates) {\n GenerateContentResponse response =\n GenerateContentResponse.builder().candidates(candidates).build();\n return builder().response(response).build();\n }\n\n public static LlmResponse create(GenerateContentResponse response) {\n return builder().response(response).build();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/agents/BaseAgent.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.agents;\n\nimport static com.google.common.collect.ImmutableList.toImmutableList;\n\nimport com.google.adk.Telemetry;\nimport com.google.adk.agents.Callbacks.AfterAgentCallback;\nimport com.google.adk.agents.Callbacks.BeforeAgentCallback;\nimport com.google.adk.events.Event;\nimport com.google.common.collect.ImmutableList;\nimport com.google.genai.types.Content;\nimport io.opentelemetry.api.trace.Span;\nimport io.opentelemetry.api.trace.Tracer;\nimport io.opentelemetry.context.Scope;\nimport io.reactivex.rxjava3.core.Flowable;\nimport io.reactivex.rxjava3.core.Maybe;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.function.Function;\nimport org.jspecify.annotations.Nullable;\n\n/** Base class for all agents. */\npublic abstract class BaseAgent {\n\n /** The agent's name. Must be a unique identifier within the agent tree. */\n private final String name;\n\n /**\n * One line description about the agent's capability. The system can use this for decision-making\n * when delegating control to different agents.\n */\n private final String description;\n\n /**\n * The parent agent in the agent tree. Note that one agent cannot be added to two different\n * parents' sub-agents lists.\n */\n private BaseAgent parentAgent;\n\n private final List subAgents;\n\n private final Optional> beforeAgentCallback;\n private final Optional> afterAgentCallback;\n\n /**\n * Creates a new BaseAgent.\n *\n * @param name Unique agent name. Cannot be \"user\" (reserved).\n * @param description Agent purpose.\n * @param subAgents Agents managed by this agent.\n * @param beforeAgentCallback Callbacks before agent execution. Invoked in order until one doesn't\n * return null.\n * @param afterAgentCallback Callbacks after agent execution. Invoked in order until one doesn't\n * return null.\n */\n public BaseAgent(\n String name,\n String description,\n List subAgents,\n List beforeAgentCallback,\n List afterAgentCallback) {\n this.name = name;\n this.description = description;\n this.parentAgent = null;\n this.subAgents = subAgents != null ? subAgents : ImmutableList.of();\n this.beforeAgentCallback = Optional.ofNullable(beforeAgentCallback);\n this.afterAgentCallback = Optional.ofNullable(afterAgentCallback);\n\n // Establish parent relationships for all sub-agents if needed.\n for (BaseAgent subAgent : this.subAgents) {\n subAgent.parentAgent(this);\n }\n }\n\n /**\n * Gets the agent's unique name.\n *\n * @return the unique name of the agent.\n */\n public final String name() {\n return name;\n }\n\n /**\n * Gets the one-line description of the agent's capability.\n *\n * @return the description of the agent.\n */\n public final String description() {\n return description;\n }\n\n /**\n * Retrieves the parent agent in the agent tree.\n *\n * @return the parent agent, or {@code null} if this agent does not have a parent.\n */\n public BaseAgent parentAgent() {\n return parentAgent;\n }\n\n /**\n * Sets the parent agent.\n *\n * @param parentAgent The parent agent to set.\n */\n protected void parentAgent(BaseAgent parentAgent) {\n this.parentAgent = parentAgent;\n }\n\n /**\n * Returns the root agent for this agent by traversing up the parent chain.\n *\n * @return the root agent.\n */\n public BaseAgent rootAgent() {\n BaseAgent agent = this;\n while (agent.parentAgent() != null) {\n agent = agent.parentAgent();\n }\n return agent;\n }\n\n /**\n * Finds an agent (this or descendant) by name.\n *\n * @return the agent or descendant with the given name, or {@code null} if not found.\n */\n public BaseAgent findAgent(String name) {\n if (this.name().equals(name)) {\n return this;\n }\n return findSubAgent(name);\n }\n\n /** Recursively search sub agent by name. */\n public @Nullable BaseAgent findSubAgent(String name) {\n for (BaseAgent subAgent : subAgents) {\n if (subAgent.name().equals(name)) {\n return subAgent;\n }\n BaseAgent result = subAgent.findSubAgent(name);\n if (result != null) {\n return result;\n }\n }\n return null;\n }\n\n public List subAgents() {\n return subAgents;\n }\n\n public Optional> beforeAgentCallback() {\n return beforeAgentCallback;\n }\n\n public Optional> afterAgentCallback() {\n return afterAgentCallback;\n }\n\n /**\n * Creates a shallow copy of the parent context with the agent properly being set to this\n * instance.\n *\n * @param parentContext Parent context to copy.\n * @return new context with updated branch name.\n */\n private InvocationContext createInvocationContext(InvocationContext parentContext) {\n InvocationContext invocationContext = InvocationContext.copyOf(parentContext);\n invocationContext.agent(this);\n // Check for branch to be truthy (not None, not empty string),\n if (parentContext.branch().filter(s -> !s.isEmpty()).isPresent()) {\n invocationContext.branch(parentContext.branch().get() + \".\" + name());\n }\n return invocationContext;\n }\n\n /**\n * Runs the agent asynchronously.\n *\n * @param parentContext Parent context to inherit.\n * @return stream of agent-generated events.\n */\n public Flowable runAsync(InvocationContext parentContext) {\n Tracer tracer = Telemetry.getTracer();\n return Flowable.defer(\n () -> {\n Span span = tracer.spanBuilder(\"agent_run [\" + name() + \"]\").startSpan();\n try (Scope scope = span.makeCurrent()) {\n InvocationContext invocationContext = createInvocationContext(parentContext);\n\n Flowable executionFlowable =\n beforeAgentCallback\n .map(\n callback ->\n callCallback(beforeCallbacksToFunctions(callback), invocationContext))\n .orElse(Single.just(Optional.empty()))\n .flatMapPublisher(\n beforeEventOpt -> {\n if (invocationContext.endInvocation()) {\n return Flowable.fromOptional(beforeEventOpt);\n }\n\n Flowable beforeEvents = Flowable.fromOptional(beforeEventOpt);\n Flowable mainEvents =\n Flowable.defer(() -> runAsyncImpl(invocationContext));\n Flowable afterEvents =\n afterAgentCallback\n .map(\n callback ->\n Flowable.defer(\n () ->\n callCallback(\n afterCallbacksToFunctions(callback),\n invocationContext)\n .flatMapPublisher(Flowable::fromOptional)))\n .orElse(Flowable.empty());\n\n return Flowable.concat(beforeEvents, mainEvents, afterEvents);\n });\n return executionFlowable.doFinally(span::end);\n }\n });\n }\n\n /**\n * Converts before-agent callbacks to functions.\n *\n * @param callbacks Before-agent callbacks.\n * @return callback functions.\n */\n private ImmutableList>> beforeCallbacksToFunctions(\n List callbacks) {\n return callbacks.stream()\n .map(callback -> (Function>) callback::call)\n .collect(toImmutableList());\n }\n\n /**\n * Converts after-agent callbacks to functions.\n *\n * @param callbacks After-agent callbacks.\n * @return callback functions.\n */\n private ImmutableList>> afterCallbacksToFunctions(\n List callbacks) {\n return callbacks.stream()\n .map(callback -> (Function>) callback::call)\n .collect(toImmutableList());\n }\n\n /**\n * Calls agent callbacks and returns the first produced event, if any.\n *\n * @param agentCallbacks Callback functions.\n * @param invocationContext Current invocation context.\n * @return single emitting first event, or empty if none.\n */\n private Single> callCallback(\n List>> agentCallbacks,\n InvocationContext invocationContext) {\n if (agentCallbacks == null || agentCallbacks.isEmpty()) {\n return Single.just(Optional.empty());\n }\n\n CallbackContext callbackContext =\n new CallbackContext(invocationContext, /* eventActions= */ null);\n\n return Flowable.fromIterable(agentCallbacks)\n .concatMap(\n callback -> {\n Maybe maybeContent = callback.apply(callbackContext);\n\n return maybeContent\n .map(\n content -> {\n Event.Builder eventBuilder =\n Event.builder()\n .id(Event.generateEventId())\n .invocationId(invocationContext.invocationId())\n .author(name())\n .branch(invocationContext.branch())\n .actions(callbackContext.eventActions());\n\n eventBuilder.content(Optional.of(content));\n invocationContext.setEndInvocation(true);\n return Optional.of(eventBuilder.build());\n })\n .toFlowable();\n })\n .firstElement()\n .switchIfEmpty(\n Single.defer(\n () -> {\n if (callbackContext.state().hasDelta()) {\n Event.Builder eventBuilder =\n Event.builder()\n .id(Event.generateEventId())\n .invocationId(invocationContext.invocationId())\n .author(name())\n .branch(invocationContext.branch())\n .actions(callbackContext.eventActions());\n\n return Single.just(Optional.of(eventBuilder.build()));\n } else {\n return Single.just(Optional.empty());\n }\n }));\n }\n\n /**\n * Runs the agent synchronously.\n *\n * @param parentContext Parent context to inherit.\n * @return stream of agent-generated events.\n */\n public Flowable runLive(InvocationContext parentContext) {\n Tracer tracer = Telemetry.getTracer();\n return Flowable.defer(\n () -> {\n Span span = tracer.spanBuilder(\"agent_run [\" + name() + \"]\").startSpan();\n try (Scope scope = span.makeCurrent()) {\n InvocationContext invocationContext = createInvocationContext(parentContext);\n Flowable executionFlowable = runLiveImpl(invocationContext);\n return executionFlowable.doFinally(span::end);\n }\n });\n }\n\n /**\n * Agent-specific asynchronous logic.\n *\n * @param invocationContext Current invocation context.\n * @return stream of agent-generated events.\n */\n protected abstract Flowable runAsyncImpl(InvocationContext invocationContext);\n\n /**\n * Agent-specific synchronous logic.\n *\n * @param invocationContext Current invocation context.\n * @return stream of agent-generated events.\n */\n protected abstract Flowable runLiveImpl(InvocationContext invocationContext);\n}\n"], ["/adk-java/dev/src/main/java/com/google/adk/web/AgentCompilerLoader.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.web;\n\nimport com.google.adk.agents.BaseAgent;\nimport com.google.adk.web.config.AgentLoadingProperties;\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.PrintWriter;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Modifier;\nimport java.net.URISyntaxException;\nimport java.net.URL;\nimport java.net.URLClassLoader;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.nio.file.StandardCopyOption;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.LinkedHashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\nimport org.eclipse.jdt.core.compiler.batch.BatchCompiler;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.stereotype.Service;\n\n/**\n * Dynamically compiles and loads ADK {@link BaseAgent} implementations from source files. It\n * orchestrates the discovery of the ADK core JAR, compilation of agent sources using the Eclipse\n * JDT (ECJ) compiler, and loading of compiled agents into isolated classloaders. Agents are\n * identified by a public static field named {@code ROOT_AGENT}. Supports agent organization in\n * subdirectories or as individual {@code .java} files.\n */\n@Service\npublic class AgentCompilerLoader {\n private static final Logger logger = LoggerFactory.getLogger(AgentCompilerLoader.class);\n private final AgentLoadingProperties properties;\n private Path compiledAgentsOutputDir;\n private final String adkCoreJarPathForCompilation;\n\n /**\n * Initializes the loader with agent configuration and proactively attempts to locate the ADK core\n * JAR. This JAR, containing {@link BaseAgent} and other core ADK types, is crucial for agent\n * compilation. The location strategy (see {@link #locateAndPrepareAdkCoreJar()}) includes\n * handling directly available JARs and extracting nested JARs (e.g., in Spring Boot fat JARs) to\n * ensure it's available for the compilation classpath.\n *\n * @param properties Configuration detailing agent source locations and compilation settings.\n */\n public AgentCompilerLoader(AgentLoadingProperties properties) {\n this.properties = properties;\n this.adkCoreJarPathForCompilation = locateAndPrepareAdkCoreJar();\n }\n\n /**\n * Attempts to find the ADK core JAR, which provides {@link BaseAgent} and essential ADK classes\n * required for compiling dynamically loaded agents.\n *\n *

Strategies include:\n *\n *

    \n *
  • Checking if {@code BaseAgent.class} is loaded from a plain {@code .jar} file on the\n * classpath.\n *
  • Detecting and extracting the ADK core JAR if it's nested within a \"fat JAR\" (e.g., {@code\n * BOOT-INF/lib/} in Spring Boot applications). The extracted JAR is placed in a temporary\n * file for use during compilation.\n *
\n *\n * If located, its absolute path is returned for explicit inclusion in the compiler's classpath.\n * Returns an empty string if the JAR cannot be reliably pinpointed through these specific means,\n * in which case compilation will rely on broader classpath introspection.\n *\n * @return Absolute path to the ADK core JAR if found and prepared, otherwise an empty string.\n */\n private String locateAndPrepareAdkCoreJar() {\n try {\n URL agentClassUrl = BaseAgent.class.getProtectionDomain().getCodeSource().getLocation();\n if (agentClassUrl == null) {\n logger.warn(\"Could not get location for BaseAgent.class. ADK Core JAR might not be found.\");\n return \"\";\n }\n logger.debug(\"BaseAgent.class loaded from: {}\", agentClassUrl);\n\n if (\"file\".equals(agentClassUrl.getProtocol())) {\n Path path = Paths.get(agentClassUrl.toURI());\n if (path.toString().endsWith(\".jar\") && Files.exists(path)) {\n logger.debug(\n \"ADK Core JAR (or where BaseAgent resides) found directly on classpath: {}\",\n path.toAbsolutePath());\n return path.toAbsolutePath().toString();\n } else if (Files.isDirectory(path)) {\n logger.debug(\n \"BaseAgent.class found in directory (e.g., target/classes): {}. This path will be\"\n + \" part of classloader introspection.\",\n path.toAbsolutePath());\n return \"\";\n }\n } else if (\"jar\".equals(agentClassUrl.getProtocol())) { // Typically for nested JARs\n String urlPath = agentClassUrl.getPath();\n if (urlPath.startsWith(\"file:\")) {\n urlPath = urlPath.substring(\"file:\".length());\n }\n int firstSeparator = urlPath.indexOf(\"!/\");\n if (firstSeparator == -1) {\n logger.warn(\"Malformed JAR URL for BaseAgent.class: {}\", agentClassUrl);\n return \"\";\n }\n\n String mainJarPath = urlPath.substring(0, firstSeparator);\n String nestedPath = urlPath.substring(firstSeparator);\n\n if (nestedPath.startsWith(\"!/BOOT-INF/lib/\") && nestedPath.contains(\"google-adk-\")) {\n int nestedJarStartInPath = \"!/BOOT-INF/lib/\".length();\n int nestedJarEndInPath = nestedPath.indexOf(\"!/\", nestedJarStartInPath);\n if (nestedJarEndInPath > 0) {\n String nestedJarName = nestedPath.substring(nestedJarStartInPath, nestedJarEndInPath);\n String nestedJarUrlString =\n \"jar:file:\" + mainJarPath + \"!/BOOT-INF/lib/\" + nestedJarName;\n\n Path tempFile = Files.createTempFile(\"adk-core-extracted-\", \".jar\");\n try (InputStream is = new URL(nestedJarUrlString).openStream()) {\n Files.copy(is, tempFile, StandardCopyOption.REPLACE_EXISTING);\n }\n tempFile.toFile().deleteOnExit();\n logger.debug(\n \"Extracted ADK Core JAR '{}' from nested location to: {}\",\n nestedJarName,\n tempFile.toAbsolutePath());\n return tempFile.toAbsolutePath().toString();\n }\n } else if (mainJarPath.contains(\"google-adk-\") && mainJarPath.endsWith(\".jar\")) {\n File adkJar = new File(mainJarPath);\n if (adkJar.exists()) {\n logger.debug(\"ADK Core JAR identified as the outer JAR: {}\", adkJar.getAbsolutePath());\n return adkJar.getAbsolutePath();\n }\n }\n }\n } catch (Exception e) {\n logger.error(\"Error trying to locate or extract ADK Core JAR\", e);\n }\n logger.warn(\n \"ADK Core JAR could not be reliably located for compilation via locateAndPrepareAdkCoreJar.\"\n + \" Relying on classloader introspection.\");\n return \"\";\n }\n\n /**\n * Discovers, compiles, and loads agents from the configured source directory.\n *\n *

The process for each potential \"agent unit\" (a subdirectory or a root {@code .java} file):\n *\n *

    \n *
  1. Collects {@code .java} source files.\n *
  2. Compiles these sources using ECJ (see {@link #compileSourcesWithECJ(List, Path)}) into a\n * temporary, unit-specific output directory. This directory is cleaned up on JVM exit.\n *
  3. Creates a dedicated {@link URLClassLoader} for the compiled unit, isolating its classes.\n *
  4. Scans compiled classes for a public static field {@code ROOT_AGENT} assignable to {@link\n * BaseAgent}. This field serves as the designated entry point for an agent.\n *
  5. Instantiates and stores the {@link BaseAgent} if found, keyed by its name.\n *
\n *\n * This approach allows for dynamic addition of agents without pre-compilation and supports\n * independent classpaths per agent unit if needed (though current implementation uses a shared\n * parent classloader).\n *\n * @return A map of successfully loaded agent names to their {@link BaseAgent} instances. Returns\n * an empty map if the source directory isn't configured or no agents are found.\n * @throws IOException If an I/O error occurs (e.g., creating temp directories, reading sources).\n */\n public Map loadAgents() throws IOException {\n if (properties.getSourceDir() == null || properties.getSourceDir().isEmpty()) {\n logger.info(\n \"Agent source directory (adk.agents.source-dir) not configured. No dynamic agents will be\"\n + \" loaded.\");\n return Collections.emptyMap();\n }\n\n Path agentsSourceRoot = Paths.get(properties.getSourceDir());\n if (!Files.isDirectory(agentsSourceRoot)) {\n logger.warn(\"Agent source directory does not exist: {}\", agentsSourceRoot);\n return Collections.emptyMap();\n }\n\n this.compiledAgentsOutputDir = Files.createTempDirectory(\"adk-compiled-agents-\");\n this.compiledAgentsOutputDir.toFile().deleteOnExit();\n logger.debug(\"Compiling agents from {} to {}\", agentsSourceRoot, compiledAgentsOutputDir);\n\n Map loadedAgents = new HashMap<>();\n\n try (Stream stream = Files.list(agentsSourceRoot)) {\n List entries = stream.collect(Collectors.toList());\n\n for (Path entry : entries) {\n List javaFilesToCompile = new ArrayList<>();\n String agentUnitName;\n\n if (Files.isDirectory(entry)) {\n agentUnitName = entry.getFileName().toString();\n logger.debug(\"Processing agent sources from directory: {}\", agentUnitName);\n try (Stream javaFilesStream =\n Files.walk(entry)\n .filter(p -> p.toString().endsWith(\".java\") && Files.isRegularFile(p))) {\n javaFilesToCompile =\n javaFilesStream\n .map(p -> p.toAbsolutePath().toString())\n .collect(Collectors.toList());\n }\n } else if (Files.isRegularFile(entry) && entry.getFileName().toString().endsWith(\".java\")) {\n String fileName = entry.getFileName().toString();\n agentUnitName = fileName.substring(0, fileName.length() - \".java\".length());\n logger.debug(\"Processing agent source file: {}\", entry.getFileName());\n javaFilesToCompile.add(entry.toAbsolutePath().toString());\n } else {\n logger.trace(\"Skipping non-agent entry in agent source root: {}\", entry.getFileName());\n continue;\n }\n\n if (javaFilesToCompile.isEmpty()) {\n logger.debug(\"No .java files found for agent unit: {}\", agentUnitName);\n continue;\n }\n\n Path unitSpecificOutputDir = compiledAgentsOutputDir.resolve(agentUnitName);\n Files.createDirectories(unitSpecificOutputDir);\n\n boolean compilationSuccess =\n compileSourcesWithECJ(javaFilesToCompile, unitSpecificOutputDir);\n\n if (compilationSuccess) {\n try {\n List classLoaderUrls = new ArrayList<>();\n classLoaderUrls.add(unitSpecificOutputDir.toUri().toURL());\n\n URLClassLoader agentClassLoader =\n new URLClassLoader(\n classLoaderUrls.toArray(new URL[0]),\n AgentCompilerLoader.class.getClassLoader());\n\n Files.walk(unitSpecificOutputDir)\n .filter(p -> p.toString().endsWith(\".class\"))\n .forEach(\n classFile -> {\n try {\n String relativePath =\n unitSpecificOutputDir.relativize(classFile).toString();\n String className =\n relativePath\n .substring(0, relativePath.length() - \".class\".length())\n .replace(File.separatorChar, '.');\n\n Class loadedClass = agentClassLoader.loadClass(className);\n Field rootAgentField = null;\n try {\n rootAgentField = loadedClass.getField(\"ROOT_AGENT\");\n } catch (NoSuchFieldException e) {\n return;\n }\n\n if (Modifier.isStatic(rootAgentField.getModifiers())\n && BaseAgent.class.isAssignableFrom(rootAgentField.getType())) {\n BaseAgent agentInstance = (BaseAgent) rootAgentField.get(null);\n if (agentInstance != null) {\n if (loadedAgents.containsKey(agentInstance.name())) {\n logger.warn(\n \"Found another agent with name {}. This will overwrite the\"\n + \" original agent loaded with this name from unit {} using\"\n + \" class {}\",\n agentInstance.name(),\n agentUnitName,\n className);\n }\n loadedAgents.put(agentInstance.name(), agentInstance);\n logger.debug(\n \"Successfully loaded agent '{}' from unit: {} using class {}\",\n agentInstance.name(),\n agentUnitName,\n className);\n } else {\n logger.warn(\n \"ROOT_AGENT field in class {} from unit {} was null\",\n className,\n agentUnitName);\n }\n }\n } catch (ClassNotFoundException | IllegalAccessException e) {\n logger.error(\n \"Error loading or accessing agent from class file {} for unit {}\",\n classFile,\n agentUnitName,\n e);\n } catch (Exception e) {\n logger.error(\n \"Unexpected error processing class file {} for unit {}\",\n classFile,\n agentUnitName,\n e);\n }\n });\n } catch (Exception e) {\n logger.error(\n \"Error during class loading setup for unit {}: {}\",\n agentUnitName,\n e.getMessage(),\n e);\n }\n } else {\n logger.error(\"Compilation failed for agent unit: {}\", agentUnitName);\n }\n }\n }\n return loadedAgents;\n }\n\n /**\n * Compiles the given Java source files using the Eclipse JDT (ECJ) batch compiler.\n *\n *

Key aspects of the compilation process:\n *\n *

    \n *
  • Sets Java version to 17 (to align with core ADK library) and suppresses warnings by\n * default.\n *
  • Constructs the compilation classpath by:\n *
      \n *
    1. Introspecting the current classloader hierarchy ({@link URLClassLoader} instances)\n * to gather available JARs and class directories.\n *
    2. Falling back to {@code System.getProperty(\"java.class.path\")} if introspection\n * yields no results.\n *
    3. Explicitly adding the ADK Core JAR path (determined by {@link\n * #locateAndPrepareAdkCoreJar()}) to ensure {@link BaseAgent} and related types are\n * resolvable.\n *
    4. Appending any user-defined classpath entries from {@link\n * AgentLoadingProperties#getCompileClasspath()}.\n *
    \n *
  • Outputs compiled {@code .class} files to the specified {@code outputDir}.\n *
\n *\n * This method aims to provide a robust classpath for compiling agents in various runtime\n * environments, including IDEs, standard Java executions, and fat JAR deployments.\n *\n * @param javaFilePaths A list of absolute paths to {@code .java} files to be compiled.\n * @param outputDir The directory where compiled {@code .class} files will be placed.\n * @return {@code true} if compilation succeeds, {@code false} otherwise.\n */\n private boolean compileSourcesWithECJ(List javaFilePaths, Path outputDir) {\n List ecjArgs = new ArrayList<>();\n ecjArgs.add(\"-17\"); // Java version\n ecjArgs.add(\"-nowarn\");\n ecjArgs.add(\"-d\");\n ecjArgs.add(outputDir.toAbsolutePath().toString());\n\n Set classpathEntries = new LinkedHashSet<>();\n\n logger.debug(\"Attempting to derive ECJ classpath from classloader hierarchy...\");\n ClassLoader currentClassLoader = AgentCompilerLoader.class.getClassLoader();\n int classLoaderCount = 0;\n while (currentClassLoader != null) {\n classLoaderCount++;\n logger.debug(\n \"Inspecting classloader ({}) : {}\",\n classLoaderCount,\n currentClassLoader.getClass().getName());\n if (currentClassLoader instanceof java.net.URLClassLoader) {\n URL[] urls = ((java.net.URLClassLoader) currentClassLoader).getURLs();\n logger.debug(\n \" Found {} URLs in URLClassLoader {}\",\n urls.length,\n currentClassLoader.getClass().getName());\n for (URL url : urls) {\n try {\n if (\"file\".equals(url.getProtocol())) {\n String path = Paths.get(url.toURI()).toString();\n classpathEntries.add(path);\n logger.trace(\" Added to ECJ classpath: {}\", path);\n } else {\n logger.debug(\n \" Skipping non-file URL from classloader {}: {}\",\n currentClassLoader.getClass().getName(),\n url);\n }\n } catch (URISyntaxException | IllegalArgumentException e) {\n logger.warn(\n \" Could not convert URL to path or add to classpath from {}: {} (Error: {})\",\n currentClassLoader.getClass().getName(),\n url,\n e.getMessage());\n } catch (Exception e) {\n logger.warn(\n \" Unexpected error converting URL to path from {}: {} (Error: {})\",\n currentClassLoader.getClass().getName(),\n url,\n e.getMessage(),\n e);\n }\n }\n }\n currentClassLoader = currentClassLoader.getParent();\n }\n\n if (classpathEntries.isEmpty()) {\n logger.warn(\n \"No classpath entries derived from classloader hierarchy. \"\n + \"Falling back to System.getProperty(\\\"java.class.path\\\").\");\n String systemClasspath = System.getProperty(\"java.class.path\");\n if (systemClasspath != null && !systemClasspath.isEmpty()) {\n logger.debug(\"Using system classpath for ECJ (fallback): {}\", systemClasspath);\n classpathEntries.addAll(Arrays.asList(systemClasspath.split(File.pathSeparator)));\n } else {\n logger.error(\"System classpath (java.class.path) is also null or empty.\");\n }\n }\n\n if (this.adkCoreJarPathForCompilation != null && !this.adkCoreJarPathForCompilation.isEmpty()) {\n if (!classpathEntries.contains(this.adkCoreJarPathForCompilation)) {\n logger.debug(\n \"Adding ADK Core JAR path explicitly to ECJ classpath: {}\",\n this.adkCoreJarPathForCompilation);\n classpathEntries.add(this.adkCoreJarPathForCompilation);\n } else {\n logger.debug(\n \"ADK Core JAR path ({}) already found in derived ECJ classpath.\",\n this.adkCoreJarPathForCompilation);\n }\n } else if (classpathEntries.stream().noneMatch(p -> p.contains(\"google-adk\"))) {\n logger.error(\n \"ADK Core JAR path is missing and no 'google-adk' JAR found in derived classpath. \"\n + \"Compilation will likely fail to find BaseAgent.\");\n }\n\n if (properties.getCompileClasspath() != null && !properties.getCompileClasspath().isEmpty()) {\n String userClasspath = properties.getCompileClasspath();\n logger.info(\n \"Appending user-defined classpath (adk.agents.compile-classpath) to ECJ: {}\",\n userClasspath);\n classpathEntries.addAll(Arrays.asList(userClasspath.split(File.pathSeparator)));\n }\n\n if (!classpathEntries.isEmpty()) {\n String effectiveClasspath =\n classpathEntries.stream().collect(Collectors.joining(File.pathSeparator));\n ecjArgs.add(\"-cp\");\n ecjArgs.add(effectiveClasspath);\n logger.debug(\"Constructed ECJ classpath with {} entries\", classpathEntries.size());\n logger.debug(\"Final effective ECJ classpath: {}\", effectiveClasspath);\n } else {\n logger.error(\"ECJ Classpath is empty after all attempts. Compilation will fail.\");\n return false;\n }\n\n ecjArgs.addAll(javaFilePaths);\n\n logger.debug(\"ECJ Args: {}\", String.join(\" \", ecjArgs));\n\n PrintWriter outWriter = new PrintWriter(System.out, true);\n PrintWriter errWriter = new PrintWriter(System.err, true);\n\n boolean success =\n BatchCompiler.compile(ecjArgs.toArray(new String[0]), outWriter, errWriter, null);\n if (!success) {\n logger.error(\"ECJ Compilation failed. See console output for details.\");\n }\n return success;\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/artifacts/GcsArtifactService.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.artifacts;\n\nimport static java.util.Collections.max;\n\nimport com.google.cloud.storage.Blob;\nimport com.google.cloud.storage.BlobId;\nimport com.google.cloud.storage.BlobInfo;\nimport com.google.cloud.storage.Storage;\nimport com.google.cloud.storage.Storage.BlobListOption;\nimport com.google.cloud.storage.StorageException;\nimport com.google.common.base.Splitter;\nimport com.google.common.base.VerifyException;\nimport com.google.common.collect.ImmutableList;\nimport com.google.genai.types.Part;\nimport io.reactivex.rxjava3.core.Completable;\nimport io.reactivex.rxjava3.core.Maybe;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.Set;\n\n/** An artifact service implementation using Google Cloud Storage (GCS). */\npublic final class GcsArtifactService implements BaseArtifactService {\n private final String bucketName;\n private final Storage storageClient;\n\n /**\n * Initializes the GcsArtifactService.\n *\n * @param bucketName The name of the GCS bucket to use.\n * @param storageClient The GCS storage client instance.\n */\n public GcsArtifactService(String bucketName, Storage storageClient) {\n this.bucketName = bucketName;\n this.storageClient = storageClient;\n }\n\n /**\n * Checks if a filename uses the user namespace.\n *\n * @param filename Filename to check.\n * @return true if prefixed with \"user:\", false otherwise.\n */\n private boolean fileHasUserNamespace(String filename) {\n return filename != null && filename.startsWith(\"user:\");\n }\n\n /**\n * Constructs the blob prefix for an artifact (excluding version).\n *\n * @param appName Application name.\n * @param userId User ID.\n * @param sessionId Session ID.\n * @param filename Artifact filename.\n * @return prefix string for blob location.\n */\n private String getBlobPrefix(String appName, String userId, String sessionId, String filename) {\n if (fileHasUserNamespace(filename)) {\n return String.format(\"%s/%s/user/%s/\", appName, userId, filename);\n } else {\n return String.format(\"%s/%s/%s/%s/\", appName, userId, sessionId, filename);\n }\n }\n\n /**\n * Constructs the full blob name for an artifact, including version.\n *\n * @param appName Application name.\n * @param userId User ID.\n * @param sessionId Session ID.\n * @param filename Artifact filename.\n * @param version Artifact version.\n * @return full blob name.\n */\n private String getBlobName(\n String appName, String userId, String sessionId, String filename, int version) {\n return getBlobPrefix(appName, userId, sessionId, filename) + version;\n }\n\n /**\n * Saves an artifact to GCS and assigns a new version.\n *\n * @param appName Application name.\n * @param userId User ID.\n * @param sessionId Session ID.\n * @param filename Artifact filename.\n * @param artifact Artifact content to save.\n * @return Single with assigned version number.\n */\n @Override\n public Single saveArtifact(\n String appName, String userId, String sessionId, String filename, Part artifact) {\n return listVersions(appName, userId, sessionId, filename)\n .map(versions -> versions.isEmpty() ? 0 : max(versions) + 1)\n .map(\n nextVersion -> {\n String blobName = getBlobName(appName, userId, sessionId, filename, nextVersion);\n BlobId blobId = BlobId.of(bucketName, blobName);\n\n BlobInfo blobInfo =\n BlobInfo.newBuilder(blobId)\n .setContentType(artifact.inlineData().get().mimeType().orElse(null))\n .build();\n\n try {\n byte[] dataToSave =\n artifact\n .inlineData()\n .get()\n .data()\n .orElseThrow(\n () ->\n new IllegalArgumentException(\n \"Saveable artifact data must be non-empty.\"));\n storageClient.create(blobInfo, dataToSave);\n return nextVersion;\n } catch (StorageException e) {\n throw new VerifyException(\"Failed to save artifact to GCS\", e);\n }\n });\n }\n\n /**\n * Loads an artifact from GCS.\n *\n * @param appName Application name.\n * @param userId User ID.\n * @param sessionId Session ID.\n * @param filename Artifact filename.\n * @param version Optional version to load. Loads latest if empty.\n * @return Maybe with loaded artifact, or empty if not found.\n */\n @Override\n public Maybe loadArtifact(\n String appName, String userId, String sessionId, String filename, Optional version) {\n return version\n .map(Maybe::just)\n .orElseGet(\n () ->\n listVersions(appName, userId, sessionId, filename)\n .flatMapMaybe(\n versions -> versions.isEmpty() ? Maybe.empty() : Maybe.just(max(versions))))\n .flatMap(\n versionToLoad -> {\n String blobName = getBlobName(appName, userId, sessionId, filename, versionToLoad);\n BlobId blobId = BlobId.of(bucketName, blobName);\n\n try {\n Blob blob = storageClient.get(blobId);\n if (blob == null || !blob.exists()) {\n return Maybe.empty();\n }\n byte[] data = blob.getContent();\n String mimeType = blob.getContentType();\n return Maybe.just(Part.fromBytes(data, mimeType));\n } catch (StorageException e) {\n return Maybe.empty();\n }\n });\n }\n\n /**\n * Lists artifact filenames for a user and session.\n *\n * @param appName Application name.\n * @param userId User ID.\n * @param sessionId Session ID.\n * @return Single with sorted list of artifact filenames.\n */\n @Override\n public Single listArtifactKeys(\n String appName, String userId, String sessionId) {\n Set filenames = new HashSet<>();\n\n // List session-specific files\n String sessionPrefix = String.format(\"%s/%s/%s/\", appName, userId, sessionId);\n try {\n for (Blob blob :\n storageClient.list(bucketName, BlobListOption.prefix(sessionPrefix)).iterateAll()) {\n List parts = Splitter.on('/').splitToList(blob.getName());\n filenames.add(parts.get(3)); // appName/userId/sessionId/filename/version\n }\n } catch (StorageException e) {\n throw new VerifyException(\"Failed to list session artifacts from GCS\", e);\n }\n\n // List user-namespace files\n String userPrefix = String.format(\"%s/%s/user/\", appName, userId);\n try {\n for (Blob blob :\n storageClient.list(bucketName, BlobListOption.prefix(userPrefix)).iterateAll()) {\n List parts = Splitter.on('/').splitToList(blob.getName());\n filenames.add(parts.get(3)); // appName/userId/user/filename/version\n }\n } catch (StorageException e) {\n throw new VerifyException(\"Failed to list user artifacts from GCS\", e);\n }\n\n return Single.just(\n ListArtifactsResponse.builder().filenames(ImmutableList.sortedCopyOf(filenames)).build());\n }\n\n /**\n * Deletes all versions of the specified artifact from GCS.\n *\n * @param appName Application name.\n * @param userId User ID.\n * @param sessionId Session ID.\n * @param filename Artifact filename.\n * @return Completable indicating operation completion.\n */\n @Override\n public Completable deleteArtifact(\n String appName, String userId, String sessionId, String filename) {\n ImmutableList versions =\n listVersions(appName, userId, sessionId, filename).blockingGet();\n List blobIdsToDelete = new ArrayList<>();\n for (int version : versions) {\n String blobName = getBlobName(appName, userId, sessionId, filename, version);\n blobIdsToDelete.add(BlobId.of(bucketName, blobName));\n }\n\n if (!blobIdsToDelete.isEmpty()) {\n try {\n var unused = storageClient.delete(blobIdsToDelete);\n } catch (StorageException e) {\n throw new VerifyException(\"Failed to delete artifact versions from GCS\", e);\n }\n }\n return Completable.complete();\n }\n\n /**\n * Lists all available versions for a given artifact.\n *\n * @param appName Application name.\n * @param userId User ID.\n * @param sessionId Session ID.\n * @param filename Artifact filename.\n * @return Single with sorted list of version numbers.\n */\n @Override\n public Single> listVersions(\n String appName, String userId, String sessionId, String filename) {\n String prefix = getBlobPrefix(appName, userId, sessionId, filename);\n List versions = new ArrayList<>();\n try {\n for (Blob blob : storageClient.list(bucketName, BlobListOption.prefix(prefix)).iterateAll()) {\n String name = blob.getName();\n int versionDelimiterIndex = name.lastIndexOf('/'); // immediately before the version number\n if (versionDelimiterIndex != -1 && versionDelimiterIndex < name.length() - 1) {\n versions.add(Integer.parseInt(name.substring(versionDelimiterIndex + 1)));\n }\n }\n return Single.just(ImmutableList.sortedCopyOf(versions));\n } catch (StorageException e) {\n return Single.just(ImmutableList.of());\n }\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/GoogleSearchTool.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools;\n\nimport com.google.adk.models.LlmRequest;\nimport com.google.common.collect.ImmutableList;\nimport com.google.genai.types.GenerateContentConfig;\nimport com.google.genai.types.GoogleSearch;\nimport com.google.genai.types.GoogleSearchRetrieval;\nimport com.google.genai.types.Tool;\nimport io.reactivex.rxjava3.core.Completable;\nimport java.util.List;\n\n/**\n * A built-in tool that is automatically invoked by Gemini 2 models to retrieve search results from\n * Google Search.\n *\n *

This tool operates internally within the model and does not require or perform local code\n * execution.\n */\npublic final class GoogleSearchTool extends BaseTool {\n\n public GoogleSearchTool() {\n super(\"google_search\", \"google_search\");\n }\n\n @Override\n public Completable processLlmRequest(\n LlmRequest.Builder llmRequestBuilder, ToolContext toolContext) {\n\n GenerateContentConfig.Builder configBuilder =\n llmRequestBuilder\n .build()\n .config()\n .map(GenerateContentConfig::toBuilder)\n .orElse(GenerateContentConfig.builder());\n\n List existingTools = configBuilder.build().tools().orElse(ImmutableList.of());\n ImmutableList.Builder updatedToolsBuilder = ImmutableList.builder();\n updatedToolsBuilder.addAll(existingTools);\n\n String model = llmRequestBuilder.build().model().get();\n if (model != null && model.startsWith(\"gemini-1\")) {\n if (!updatedToolsBuilder.build().isEmpty()) {\n System.out.println(configBuilder.build().tools().get());\n return Completable.error(\n new IllegalArgumentException(\n \"Google search tool cannot be used with other tools in Gemini 1.x.\"));\n }\n updatedToolsBuilder.add(\n Tool.builder().googleSearchRetrieval(GoogleSearchRetrieval.builder().build()).build());\n configBuilder.tools(updatedToolsBuilder.build());\n } else if (model != null && model.startsWith(\"gemini-2\")) {\n\n updatedToolsBuilder.add(Tool.builder().googleSearch(GoogleSearch.builder().build()).build());\n configBuilder.tools(updatedToolsBuilder.build());\n } else {\n return Completable.error(\n new IllegalArgumentException(\"Google search tool is not supported for model \" + model));\n }\n\n llmRequestBuilder.config(configBuilder.build());\n return Completable.complete();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/sessions/InMemorySessionService.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\nimport static java.util.stream.Collectors.toCollection;\n\nimport com.google.adk.events.Event;\nimport com.google.adk.events.EventActions;\nimport com.google.common.collect.ImmutableList;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport io.reactivex.rxjava3.core.Completable;\nimport io.reactivex.rxjava3.core.Maybe;\nimport io.reactivex.rxjava3.core.Single;\nimport java.time.Instant;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.Optional;\nimport java.util.UUID;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentMap;\nimport org.jspecify.annotations.Nullable;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * An in-memory implementation of {@link BaseSessionService} assuming {@link Session} objects are\n * mutable regarding their state map, events list, and last update time.\n *\n *

This implementation stores sessions, user state, and app state directly in memory using\n * concurrent maps for basic thread safety. It is suitable for testing or single-node deployments\n * where persistence is not required.\n *\n *

Note: State merging (app/user state prefixed with {@code _app_} / {@code _user_}) occurs\n * during retrieval operations ({@code getSession}, {@code createSession}).\n */\npublic final class InMemorySessionService implements BaseSessionService {\n\n private static final Logger logger = LoggerFactory.getLogger(InMemorySessionService.class);\n\n // Structure: appName -> userId -> sessionId -> Session\n private final ConcurrentMap>>\n sessions;\n // Structure: appName -> userId -> stateKey -> stateValue\n private final ConcurrentMap>>\n userState;\n // Structure: appName -> stateKey -> stateValue\n private final ConcurrentMap> appState;\n\n /** Creates a new instance of the in-memory session service with empty storage. */\n public InMemorySessionService() {\n this.sessions = new ConcurrentHashMap<>();\n this.userState = new ConcurrentHashMap<>();\n this.appState = new ConcurrentHashMap<>();\n }\n\n @Override\n public Single createSession(\n String appName,\n String userId,\n @Nullable ConcurrentMap state,\n @Nullable String sessionId) {\n Objects.requireNonNull(appName, \"appName cannot be null\");\n Objects.requireNonNull(userId, \"userId cannot be null\");\n\n String resolvedSessionId =\n Optional.ofNullable(sessionId)\n .map(String::trim)\n .filter(s -> !s.isEmpty())\n .orElseGet(() -> UUID.randomUUID().toString());\n\n // Ensure state map and events list are mutable for the new session\n ConcurrentMap initialState =\n (state == null) ? new ConcurrentHashMap<>() : new ConcurrentHashMap<>(state);\n List initialEvents = new ArrayList<>();\n\n // Assuming Session constructor or setters allow setting these mutable collections\n Session newSession =\n Session.builder(resolvedSessionId)\n .appName(appName)\n .userId(userId)\n .state(initialState)\n .events(initialEvents)\n .lastUpdateTime(Instant.now())\n .build();\n\n sessions\n .computeIfAbsent(appName, k -> new ConcurrentHashMap<>())\n .computeIfAbsent(userId, k -> new ConcurrentHashMap<>())\n .put(resolvedSessionId, newSession);\n\n // Create a mutable copy for the return value\n Session returnCopy = copySession(newSession);\n // Merge state into the copy before returning\n return Single.just(mergeWithGlobalState(appName, userId, returnCopy));\n }\n\n @Override\n public Maybe getSession(\n String appName, String userId, String sessionId, Optional configOpt) {\n Objects.requireNonNull(appName, \"appName cannot be null\");\n Objects.requireNonNull(userId, \"userId cannot be null\");\n Objects.requireNonNull(sessionId, \"sessionId cannot be null\");\n Objects.requireNonNull(configOpt, \"configOpt cannot be null\");\n\n Session storedSession =\n sessions\n .getOrDefault(appName, new ConcurrentHashMap<>())\n .getOrDefault(userId, new ConcurrentHashMap<>())\n .get(sessionId);\n\n if (storedSession == null) {\n return Maybe.empty();\n }\n\n Session sessionCopy = copySession(storedSession);\n\n // Apply filtering based on config directly to the mutable list in the copy\n GetSessionConfig config = configOpt.orElse(GetSessionConfig.builder().build());\n List eventsInCopy = sessionCopy.events();\n\n config\n .numRecentEvents()\n .ifPresent(\n num -> {\n if (!eventsInCopy.isEmpty() && num < eventsInCopy.size()) {\n // Keep the last 'num' events by removing older ones\n // Create sublist view (modifications affect original list)\n\n List eventsToRemove = eventsInCopy.subList(0, eventsInCopy.size() - num);\n eventsToRemove.clear(); // Clear the sublist view, modifying eventsInCopy\n }\n });\n\n // Only apply timestamp filter if numRecentEvents was not applied\n if (config.numRecentEvents().isEmpty() && config.afterTimestamp().isPresent()) {\n Instant threshold = config.afterTimestamp().get();\n\n eventsInCopy.removeIf(\n event -> getEventTimestampEpochSeconds(event) < threshold.getEpochSecond());\n }\n\n // Merge state into the potentially filtered copy and return\n return Maybe.just(mergeWithGlobalState(appName, userId, sessionCopy));\n }\n\n // Helper to get event timestamp as epoch seconds\n private long getEventTimestampEpochSeconds(Event event) {\n return event.timestamp() / 1000L;\n }\n\n @Override\n public Single listSessions(String appName, String userId) {\n Objects.requireNonNull(appName, \"appName cannot be null\");\n Objects.requireNonNull(userId, \"userId cannot be null\");\n\n Map userSessionsMap =\n sessions.getOrDefault(appName, new ConcurrentHashMap<>()).get(userId);\n\n if (userSessionsMap == null || userSessionsMap.isEmpty()) {\n return Single.just(ListSessionsResponse.builder().build());\n }\n\n // Create copies with empty events and state for the response\n List sessionCopies =\n userSessionsMap.values().stream()\n .map(this::copySessionMetadata)\n .collect(toCollection(ArrayList::new));\n\n return Single.just(ListSessionsResponse.builder().sessions(sessionCopies).build());\n }\n\n @Override\n public Completable deleteSession(String appName, String userId, String sessionId) {\n Objects.requireNonNull(appName, \"appName cannot be null\");\n Objects.requireNonNull(userId, \"userId cannot be null\");\n Objects.requireNonNull(sessionId, \"sessionId cannot be null\");\n\n ConcurrentMap userSessionsMap =\n sessions.getOrDefault(appName, new ConcurrentHashMap<>()).get(userId);\n\n if (userSessionsMap != null) {\n userSessionsMap.remove(sessionId);\n }\n return Completable.complete();\n }\n\n @Override\n public Single listEvents(String appName, String userId, String sessionId) {\n Objects.requireNonNull(appName, \"appName cannot be null\");\n Objects.requireNonNull(userId, \"userId cannot be null\");\n Objects.requireNonNull(sessionId, \"sessionId cannot be null\");\n\n Session storedSession =\n sessions\n .getOrDefault(appName, new ConcurrentHashMap<>())\n .getOrDefault(userId, new ConcurrentHashMap<>())\n .get(sessionId);\n\n if (storedSession == null) {\n return Single.just(ListEventsResponse.builder().build());\n }\n\n ImmutableList eventsCopy = ImmutableList.copyOf(storedSession.events());\n return Single.just(ListEventsResponse.builder().events(eventsCopy).build());\n }\n\n @CanIgnoreReturnValue\n @Override\n public Single appendEvent(Session session, Event event) {\n Objects.requireNonNull(session, \"session cannot be null\");\n Objects.requireNonNull(event, \"event cannot be null\");\n Objects.requireNonNull(session.appName(), \"session.appName cannot be null\");\n Objects.requireNonNull(session.userId(), \"session.userId cannot be null\");\n Objects.requireNonNull(session.id(), \"session.id cannot be null\");\n\n String appName = session.appName();\n String userId = session.userId();\n String sessionId = session.id();\n\n // --- Update User/App State (Same as before) ---\n EventActions actions = event.actions();\n if (actions != null) {\n Map stateDelta = actions.stateDelta();\n if (stateDelta != null && !stateDelta.isEmpty()) {\n stateDelta.forEach(\n (key, value) -> {\n if (key.startsWith(State.APP_PREFIX)) {\n String appStateKey = key.substring(State.APP_PREFIX.length());\n appState\n .computeIfAbsent(appName, k -> new ConcurrentHashMap<>())\n .put(appStateKey, value);\n } else if (key.startsWith(State.USER_PREFIX)) {\n String userStateKey = key.substring(State.USER_PREFIX.length());\n userState\n .computeIfAbsent(appName, k -> new ConcurrentHashMap<>())\n .computeIfAbsent(userId, k -> new ConcurrentHashMap<>())\n .put(userStateKey, value);\n }\n });\n }\n }\n\n BaseSessionService.super.appendEvent(session, event);\n session.lastUpdateTime(getInstantFromEvent(event));\n\n // --- Update the session stored in this service ---\n sessions\n .getOrDefault(appName, new ConcurrentHashMap<>())\n .getOrDefault(userId, new ConcurrentHashMap<>())\n .put(sessionId, session);\n\n return Single.just(event);\n }\n\n /** Converts an event's timestamp to an Instant. Adapt based on actual Event structure. */\n // TODO: have Event.timestamp() return Instant directly\n private Instant getInstantFromEvent(Event event) {\n double epochSeconds = getEventTimestampEpochSeconds(event);\n long seconds = (long) epochSeconds;\n long nanos = (long) ((epochSeconds % 1.0) * 1_000_000_000L);\n return Instant.ofEpochSecond(seconds, nanos);\n }\n\n /**\n * Creates a shallow copy of the session, but with deep copies of the mutable state map and events\n * list. Assumes Session provides necessary getters and a suitable constructor/setters.\n *\n * @param original The session to copy.\n * @return A new Session instance with copied data, including mutable collections.\n */\n private Session copySession(Session original) {\n return Session.builder(original.id())\n .appName(original.appName())\n .userId(original.userId())\n .state(new ConcurrentHashMap<>(original.state()))\n .events(new ArrayList<>(original.events()))\n .lastUpdateTime(original.lastUpdateTime())\n .build();\n }\n\n /**\n * Creates a copy of the session containing only metadata fields (ID, appName, userId, timestamp).\n * State and Events are explicitly *not* copied.\n *\n * @param original The session whose metadata to copy.\n * @return A new Session instance with only metadata fields populated.\n */\n private Session copySessionMetadata(Session original) {\n return Session.builder(original.id())\n .appName(original.appName())\n .userId(original.userId())\n .lastUpdateTime(original.lastUpdateTime())\n .build();\n }\n\n /**\n * Merges the app-specific and user-specific state into the provided *mutable* session's state\n * map.\n *\n * @param appName The application name.\n * @param userId The user ID.\n * @param session The mutable session whose state map will be augmented.\n * @return The same session instance passed in, now with merged state.\n */\n @CanIgnoreReturnValue\n private Session mergeWithGlobalState(String appName, String userId, Session session) {\n Map sessionState = session.state();\n\n // Merge App State directly into the session's state map\n appState\n .getOrDefault(appName, new ConcurrentHashMap())\n .forEach((key, value) -> sessionState.put(State.APP_PREFIX + key, value));\n\n userState\n .getOrDefault(appName, new ConcurrentHashMap<>())\n .getOrDefault(userId, new ConcurrentHashMap<>())\n .forEach((key, value) -> sessionState.put(State.USER_PREFIX + key, value));\n\n return session;\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/events/Event.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.events;\n\nimport static com.google.common.collect.ImmutableList.toImmutableList;\n\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonIgnore;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.databind.annotation.JsonDeserialize;\nimport com.google.adk.JsonBaseModel;\nimport com.google.common.collect.ImmutableList;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.FinishReason;\nimport com.google.genai.types.FunctionCall;\nimport com.google.genai.types.FunctionResponse;\nimport com.google.genai.types.GroundingMetadata;\nimport java.time.Instant;\nimport java.util.List;\nimport java.util.Objects;\nimport java.util.Optional;\nimport java.util.Set;\nimport java.util.UUID;\nimport javax.annotation.Nullable;\n\n// TODO - b/413761119 update Agent.java when resolved.\n/** Represents an event in a session. */\n@JsonDeserialize(builder = Event.Builder.class)\npublic class Event extends JsonBaseModel {\n\n private String id;\n private String invocationId;\n private String author;\n private Optional content = Optional.empty();\n private EventActions actions;\n private Optional> longRunningToolIds = Optional.empty();\n private Optional partial = Optional.empty();\n private Optional turnComplete = Optional.empty();\n private Optional errorCode = Optional.empty();\n private Optional errorMessage = Optional.empty();\n private Optional interrupted = Optional.empty();\n private Optional branch = Optional.empty();\n private Optional groundingMetadata = Optional.empty();\n private long timestamp;\n\n private Event() {}\n\n public static String generateEventId() {\n return UUID.randomUUID().toString();\n }\n\n /** The event id. */\n @JsonProperty(\"id\")\n public String id() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n /** Id of the invocation that this event belongs to. */\n @JsonProperty(\"invocationId\")\n public String invocationId() {\n return invocationId;\n }\n\n public void setInvocationId(String invocationId) {\n this.invocationId = invocationId;\n }\n\n /** The author of the event, it could be the name of the agent or \"user\" literal. */\n @JsonProperty(\"author\")\n public String author() {\n return author;\n }\n\n public void setAuthor(String author) {\n this.author = author;\n }\n\n @JsonProperty(\"content\")\n public Optional content() {\n return content;\n }\n\n public void setContent(Optional content) {\n this.content = content;\n }\n\n @JsonProperty(\"actions\")\n public EventActions actions() {\n return actions;\n }\n\n public void setActions(EventActions actions) {\n this.actions = actions;\n }\n\n /**\n * Set of ids of the long running function calls. Agent client will know from this field about\n * which function call is long running.\n */\n @JsonProperty(\"longRunningToolIds\")\n public Optional> longRunningToolIds() {\n return longRunningToolIds;\n }\n\n public void setLongRunningToolIds(Optional> longRunningToolIds) {\n this.longRunningToolIds = longRunningToolIds;\n }\n\n /**\n * partial is true for incomplete chunks from the LLM streaming response. The last chunk's partial\n * is False.\n */\n @JsonProperty(\"partial\")\n public Optional partial() {\n return partial;\n }\n\n public void setPartial(Optional partial) {\n this.partial = partial;\n }\n\n @JsonProperty(\"turnComplete\")\n public Optional turnComplete() {\n return turnComplete;\n }\n\n public void setTurnComplete(Optional turnComplete) {\n this.turnComplete = turnComplete;\n }\n\n @JsonProperty(\"errorCode\")\n public Optional errorCode() {\n return errorCode;\n }\n\n public void setErrorCode(Optional errorCode) {\n this.errorCode = errorCode;\n }\n\n @JsonProperty(\"errorMessage\")\n public Optional errorMessage() {\n return errorMessage;\n }\n\n public void setErrorMessage(Optional errorMessage) {\n this.errorMessage = errorMessage;\n }\n\n @JsonProperty(\"interrupted\")\n public Optional interrupted() {\n return interrupted;\n }\n\n public void setInterrupted(Optional interrupted) {\n this.interrupted = interrupted;\n }\n\n /**\n * The branch of the event. The format is like agent_1.agent_2.agent_3, where agent_1 is the\n * parent of agent_2, and agent_2 is the parent of agent_3. Branch is used when multiple sub-agent\n * shouldn't see their peer agents' conversation history.\n */\n @JsonProperty(\"branch\")\n public Optional branch() {\n return branch;\n }\n\n /**\n * Sets the branch for this event.\n *\n *

Format: agentA.agentB.agentC — shows hierarchy of nested agents.\n *\n * @param branch Branch identifier.\n */\n public void branch(@Nullable String branch) {\n this.branch = Optional.ofNullable(branch);\n }\n\n public void branch(Optional branch) {\n this.branch = branch;\n }\n\n /** The grounding metadata of the event. */\n @JsonProperty(\"groundingMetadata\")\n public Optional groundingMetadata() {\n return groundingMetadata;\n }\n\n public void setGroundingMetadata(Optional groundingMetadata) {\n this.groundingMetadata = groundingMetadata;\n }\n\n /** The timestamp of the event. */\n @JsonProperty(\"timestamp\")\n public long timestamp() {\n return timestamp;\n }\n\n public void setTimestamp(long timestamp) {\n this.timestamp = timestamp;\n }\n\n /** Returns all function calls from this event. */\n @JsonIgnore\n public final ImmutableList functionCalls() {\n return content().flatMap(Content::parts).stream()\n .flatMap(List::stream)\n .flatMap(part -> part.functionCall().stream())\n .collect(toImmutableList());\n }\n\n /** Returns all function responses from this event. */\n @JsonIgnore\n public final ImmutableList functionResponses() {\n return content().flatMap(Content::parts).stream()\n .flatMap(List::stream)\n .flatMap(part -> part.functionResponse().stream())\n .collect(toImmutableList());\n }\n\n /** Returns true if this is a final response. */\n @JsonIgnore\n public final boolean finalResponse() {\n if (actions().skipSummarization().orElse(false)\n || (longRunningToolIds().isPresent() && !longRunningToolIds().get().isEmpty())) {\n return true;\n }\n return functionCalls().isEmpty() && functionResponses().isEmpty() && !partial().orElse(false);\n }\n\n /**\n * Converts the event content into a readable string.\n *\n *

Includes text, function calls, and responses.\n *\n * @return Stringified content.\n */\n public final String stringifyContent() {\n StringBuilder sb = new StringBuilder();\n content().flatMap(Content::parts).stream()\n .flatMap(List::stream)\n .forEach(\n part -> {\n part.text().ifPresent(sb::append);\n part.functionCall()\n .ifPresent(functionCall -> sb.append(\"Function Call: \").append(functionCall));\n part.functionResponse()\n .ifPresent(\n functionResponse ->\n sb.append(\"Function Response: \").append(functionResponse));\n });\n return sb.toString();\n }\n\n /** Builder for {@link Event}. */\n public static class Builder {\n\n private String id;\n private String invocationId;\n private String author;\n private Optional content = Optional.empty();\n private EventActions actions;\n private Optional> longRunningToolIds = Optional.empty();\n private Optional partial = Optional.empty();\n private Optional turnComplete = Optional.empty();\n private Optional errorCode = Optional.empty();\n private Optional errorMessage = Optional.empty();\n private Optional interrupted = Optional.empty();\n private Optional branch = Optional.empty();\n private Optional groundingMetadata = Optional.empty();\n private Optional timestamp = Optional.empty();\n\n @JsonCreator\n private static Builder create() {\n return new Builder();\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"id\")\n public Builder id(String value) {\n this.id = value;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"invocationId\")\n public Builder invocationId(String value) {\n this.invocationId = value;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"author\")\n public Builder author(String value) {\n this.author = value;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"content\")\n public Builder content(@Nullable Content value) {\n this.content = Optional.ofNullable(value);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder content(Optional value) {\n this.content = value;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"actions\")\n public Builder actions(EventActions value) {\n this.actions = value;\n return this;\n }\n\n Optional actions() {\n return Optional.ofNullable(actions);\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"longRunningToolIds\")\n public Builder longRunningToolIds(@Nullable Set value) {\n this.longRunningToolIds = Optional.ofNullable(value);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder longRunningToolIds(Optional> value) {\n this.longRunningToolIds = value;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"partial\")\n public Builder partial(@Nullable Boolean value) {\n this.partial = Optional.ofNullable(value);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder partial(Optional value) {\n this.partial = value;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"turnComplete\")\n public Builder turnComplete(@Nullable Boolean value) {\n this.turnComplete = Optional.ofNullable(value);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder turnComplete(Optional value) {\n this.turnComplete = value;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"errorCode\")\n public Builder errorCode(@Nullable FinishReason value) {\n this.errorCode = Optional.ofNullable(value);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder errorCode(Optional value) {\n this.errorCode = value;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"errorMessage\")\n public Builder errorMessage(@Nullable String value) {\n this.errorMessage = Optional.ofNullable(value);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder errorMessage(Optional value) {\n this.errorMessage = value;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"interrupted\")\n public Builder interrupted(@Nullable Boolean value) {\n this.interrupted = Optional.ofNullable(value);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder interrupted(Optional value) {\n this.interrupted = value;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"timestamp\")\n public Builder timestamp(long value) {\n this.timestamp = Optional.of(value);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder timestamp(Optional value) {\n this.timestamp = value;\n return this;\n }\n\n // Getter for builder's timestamp, used in build()\n Optional timestamp() {\n return timestamp;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"branch\")\n public Builder branch(@Nullable String value) {\n this.branch = Optional.ofNullable(value);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder branch(Optional value) {\n this.branch = value;\n return this;\n }\n\n // Getter for builder's branch, used in build()\n Optional branch() {\n return branch;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"groundingMetadata\")\n public Builder groundingMetadata(@Nullable GroundingMetadata value) {\n this.groundingMetadata = Optional.ofNullable(value);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder groundingMetadata(Optional value) {\n this.groundingMetadata = value;\n return this;\n }\n\n Optional groundingMetadata() {\n return groundingMetadata;\n }\n\n public Event build() {\n Event event = new Event();\n event.setId(id);\n event.setInvocationId(invocationId);\n event.setAuthor(author);\n event.setContent(content);\n event.setLongRunningToolIds(longRunningToolIds);\n event.setPartial(partial);\n event.setTurnComplete(turnComplete);\n event.setErrorCode(errorCode);\n event.setErrorMessage(errorMessage);\n event.setInterrupted(interrupted);\n event.branch(branch);\n event.setGroundingMetadata(groundingMetadata);\n\n event.setActions(actions().orElse(EventActions.builder().build()));\n event.setTimestamp(timestamp().orElse(Instant.now().toEpochMilli()));\n return event;\n }\n }\n\n public static Builder builder() {\n return new Builder();\n }\n\n /** Parses an event from a JSON string. */\n public static Event fromJson(String json) {\n return fromJsonString(json, Event.class);\n }\n\n /** Creates a builder pre-filled with this event's values. */\n public Builder toBuilder() {\n Builder builder =\n new Builder()\n .id(this.id)\n .invocationId(this.invocationId)\n .author(this.author)\n .content(this.content)\n .actions(this.actions)\n .longRunningToolIds(this.longRunningToolIds)\n .partial(this.partial)\n .turnComplete(this.turnComplete)\n .errorCode(this.errorCode)\n .errorMessage(this.errorMessage)\n .interrupted(this.interrupted)\n .branch(this.branch)\n .groundingMetadata(this.groundingMetadata);\n if (this.timestamp != 0) {\n builder.timestamp(this.timestamp);\n }\n return builder;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (!(obj instanceof Event other)) {\n return false;\n }\n return timestamp == other.timestamp\n && Objects.equals(id, other.id)\n && Objects.equals(invocationId, other.invocationId)\n && Objects.equals(author, other.author)\n && Objects.equals(content, other.content)\n && Objects.equals(actions, other.actions)\n && Objects.equals(longRunningToolIds, other.longRunningToolIds)\n && Objects.equals(partial, other.partial)\n && Objects.equals(turnComplete, other.turnComplete)\n && Objects.equals(errorCode, other.errorCode)\n && Objects.equals(errorMessage, other.errorMessage)\n && Objects.equals(interrupted, other.interrupted)\n && Objects.equals(branch, other.branch)\n && Objects.equals(groundingMetadata, other.groundingMetadata);\n }\n\n @Override\n public String toString() {\n return toJson();\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(\n id,\n invocationId,\n author,\n content,\n actions,\n longRunningToolIds,\n partial,\n turnComplete,\n errorCode,\n errorMessage,\n interrupted,\n branch,\n groundingMetadata,\n timestamp);\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/AgentTool.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools;\n\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.google.adk.JsonBaseModel;\nimport com.google.adk.SchemaUtils;\nimport com.google.adk.agents.BaseAgent;\nimport com.google.adk.agents.LlmAgent;\nimport com.google.adk.events.Event;\nimport com.google.adk.runner.InMemoryRunner;\nimport com.google.adk.runner.Runner;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.FunctionDeclaration;\nimport com.google.genai.types.Part;\nimport com.google.genai.types.Schema;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.Map;\nimport java.util.Optional;\n\n/** AgentTool implements a tool that allows an agent to call another agent. */\npublic class AgentTool extends BaseTool {\n\n private final BaseAgent agent;\n private final boolean skipSummarization;\n\n public static AgentTool create(BaseAgent agent, boolean skipSummarization) {\n return new AgentTool(agent, skipSummarization);\n }\n\n public static AgentTool create(BaseAgent agent) {\n return new AgentTool(agent, false);\n }\n\n protected AgentTool(BaseAgent agent, boolean skipSummarization) {\n super(agent.name(), agent.description());\n this.agent = agent;\n this.skipSummarization = skipSummarization;\n }\n\n @Override\n public Optional declaration() {\n FunctionDeclaration.Builder builder =\n FunctionDeclaration.builder().description(this.description()).name(this.name());\n\n Optional agentInputSchema = Optional.empty();\n if (agent instanceof LlmAgent llmAgent) {\n agentInputSchema = llmAgent.inputSchema();\n }\n\n if (agentInputSchema.isPresent()) {\n builder.parameters(agentInputSchema.get());\n } else {\n builder.parameters(\n Schema.builder()\n .type(\"OBJECT\")\n .properties(ImmutableMap.of(\"request\", Schema.builder().type(\"STRING\").build()))\n .required(ImmutableList.of(\"request\"))\n .build());\n }\n return Optional.of(builder.build());\n }\n\n @Override\n public Single> runAsync(Map args, ToolContext toolContext) {\n\n if (this.skipSummarization) {\n toolContext.actions().setSkipSummarization(true);\n }\n\n Optional agentInputSchema = Optional.empty();\n if (agent instanceof LlmAgent llmAgent) {\n agentInputSchema = llmAgent.inputSchema();\n }\n\n final Content content;\n if (agentInputSchema.isPresent()) {\n SchemaUtils.validateMapOnSchema(args, agentInputSchema.get(), true);\n try {\n content =\n Content.fromParts(Part.fromText(JsonBaseModel.getMapper().writeValueAsString(args)));\n } catch (JsonProcessingException e) {\n return Single.error(\n new RuntimeException(\"Error serializing tool arguments to JSON: \" + args, e));\n }\n } else {\n Object input = args.get(\"request\");\n content = Content.fromParts(Part.fromText(input.toString()));\n }\n\n Runner runner = new InMemoryRunner(this.agent, toolContext.agentName());\n // Session state is final, can't update to toolContext state\n // session.toBuilder().setState(toolContext.getState());\n return runner\n .sessionService()\n .createSession(toolContext.agentName(), \"tmp-user\", toolContext.state(), null)\n .flatMapPublisher(session -> runner.runAsync(session.userId(), session.id(), content))\n .lastElement()\n .map(Optional::of)\n .defaultIfEmpty(Optional.empty())\n .map(\n optionalLastEvent -> {\n if (optionalLastEvent.isEmpty()) {\n return ImmutableMap.of();\n }\n Event lastEvent = optionalLastEvent.get();\n Optional outputText =\n lastEvent\n .content()\n .flatMap(Content::parts)\n .filter(parts -> !parts.isEmpty())\n .flatMap(parts -> parts.get(0).text());\n\n if (outputText.isEmpty()) {\n return ImmutableMap.of();\n }\n String output = outputText.get();\n\n Optional agentOutputSchema = Optional.empty();\n if (agent instanceof LlmAgent llmAgent) {\n agentOutputSchema = llmAgent.outputSchema();\n }\n\n if (agentOutputSchema.isPresent()) {\n return SchemaUtils.validateOutputSchema(output, agentOutputSchema.get());\n } else {\n return ImmutableMap.of(\"result\", output);\n }\n });\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/mcp/McpTool.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools.mcp;\n\nimport static java.util.concurrent.TimeUnit.MILLISECONDS;\n\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.google.adk.JsonBaseModel;\nimport com.google.adk.tools.BaseTool;\nimport com.google.adk.tools.ToolContext;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.genai.types.FunctionDeclaration;\nimport com.google.genai.types.Schema;\nimport io.modelcontextprotocol.client.McpSyncClient;\nimport io.modelcontextprotocol.spec.McpSchema.CallToolRequest;\nimport io.modelcontextprotocol.spec.McpSchema.CallToolResult;\nimport io.modelcontextprotocol.spec.McpSchema.Content;\nimport io.modelcontextprotocol.spec.McpSchema.JsonSchema;\nimport io.modelcontextprotocol.spec.McpSchema.TextContent;\nimport io.modelcontextprotocol.spec.McpSchema.Tool;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\n\n// TODO(b/413489523): Add support for auth. This is a TODO for Python as well.\n/**\n * Initializes a MCP tool.\n *\n *

This wraps a MCP Tool interface and an active MCP Session. It invokes the MCP Tool through\n * executing the tool from remote MCP Session.\n */\npublic final class McpTool extends BaseTool {\n\n Tool mcpTool;\n McpSyncClient mcpSession;\n McpSessionManager mcpSessionManager;\n ObjectMapper objectMapper;\n\n /**\n * Creates a new McpTool with the default ObjectMapper.\n *\n * @param mcpTool The MCP tool to wrap.\n * @param mcpSession The MCP session to use to call the tool.\n * @param mcpSessionManager The MCP session manager to use to create new sessions.\n * @throws IllegalArgumentException If mcpTool or mcpSession are null.\n */\n public McpTool(Tool mcpTool, McpSyncClient mcpSession, McpSessionManager mcpSessionManager) {\n this(mcpTool, mcpSession, mcpSessionManager, JsonBaseModel.getMapper());\n }\n\n /**\n * Creates a new McpTool with the default ObjectMapper.\n *\n * @param mcpTool The MCP tool to wrap.\n * @param mcpSession The MCP session to use to call the tool.\n * @param mcpSessionManager The MCP session manager to use to create new sessions.\n * @param objectMapper The ObjectMapper to use to convert JSON schemas.\n * @throws IllegalArgumentException If mcpTool or mcpSession are null.\n */\n public McpTool(\n Tool mcpTool,\n McpSyncClient mcpSession,\n McpSessionManager mcpSessionManager,\n ObjectMapper objectMapper) {\n super(\n mcpTool == null ? \"\" : mcpTool.name(),\n mcpTool == null ? \"\" : (mcpTool.description().isEmpty() ? \"\" : mcpTool.description()));\n\n if (mcpTool == null) {\n throw new IllegalArgumentException(\"mcpTool cannot be null\");\n }\n if (mcpSession == null) {\n throw new IllegalArgumentException(\"mcpSession cannot be null\");\n }\n if (objectMapper == null) {\n throw new IllegalArgumentException(\"objectMapper cannot be null\");\n }\n this.mcpTool = mcpTool;\n this.mcpSession = mcpSession;\n this.mcpSessionManager = mcpSessionManager;\n this.objectMapper = objectMapper;\n }\n\n public Schema toGeminiSchema(JsonSchema openApiSchema) {\n return Schema.fromJson(objectMapper.valueToTree(openApiSchema).toString());\n }\n\n private void reintializeSession() {\n this.mcpSession = this.mcpSessionManager.createSession();\n }\n\n @Override\n public Optional declaration() {\n return Optional.of(\n FunctionDeclaration.builder()\n .name(this.name())\n .description(this.description())\n .parameters(toGeminiSchema(this.mcpTool.inputSchema()))\n .build());\n }\n\n @Override\n public Single> runAsync(Map args, ToolContext toolContext) {\n return Single.>fromCallable(\n () -> {\n CallToolResult callResult =\n mcpSession.callTool(new CallToolRequest(this.name(), ImmutableMap.copyOf(args)));\n\n if (callResult == null) {\n return ImmutableMap.of(\"error\", \"MCP framework error: CallToolResult was null\");\n }\n\n List contents = callResult.content();\n Boolean isToolError = callResult.isError();\n\n if (isToolError != null && isToolError) {\n String errorMessage = \"Tool execution failed.\";\n if (contents != null\n && !contents.isEmpty()\n && contents.get(0) instanceof TextContent) {\n TextContent textContent = (TextContent) contents.get(0);\n if (textContent.text() != null && !textContent.text().isEmpty()) {\n errorMessage += \" Details: \" + textContent.text();\n }\n }\n return ImmutableMap.of(\"error\", errorMessage);\n }\n\n if (contents == null || contents.isEmpty()) {\n return ImmutableMap.of();\n }\n\n List textOutputs = new ArrayList<>();\n for (Content content : contents) {\n if (content instanceof TextContent textContent) {\n if (textContent.text() != null) {\n textOutputs.add(textContent.text());\n }\n }\n }\n\n if (textOutputs.isEmpty()) {\n return ImmutableMap.of(\n \"error\",\n \"Tool '\" + this.name() + \"' returned content that is not TextContent.\",\n \"content_details\",\n contents.toString());\n }\n\n List> resultMaps = new ArrayList<>();\n for (String textOutput : textOutputs) {\n try {\n resultMaps.add(\n objectMapper.readValue(\n textOutput, new TypeReference>() {}));\n } catch (JsonProcessingException e) {\n resultMaps.add(ImmutableMap.of(\"text\", textOutput));\n }\n }\n return ImmutableMap.of(\"text_output\", resultMaps);\n })\n .retryWhen(\n errors ->\n errors\n .delay(100, MILLISECONDS)\n .take(3)\n .doOnNext(\n error -> {\n System.err.println(\"Retrying callTool due to: \" + error);\n reintializeSession();\n }));\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/utils/InstructionUtils.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.utils;\n\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.sessions.Session;\nimport com.google.adk.sessions.State;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.genai.types.Part;\nimport io.reactivex.rxjava3.core.Maybe;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.regex.MatchResult;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\n/** Utility methods for handling instruction templates. */\npublic final class InstructionUtils {\n\n private static final Pattern INSTRUCTION_PLACEHOLDER_PATTERN =\n Pattern.compile(\"\\\\{+[^\\\\{\\\\}]*\\\\}+\");\n\n private InstructionUtils() {}\n\n /**\n * Populates placeholders in an instruction template string with values from the session state or\n * loaded artifacts.\n *\n *

Placeholder Syntax:\n *\n *

Placeholders are enclosed by one or more curly braces at the start and end, e.g., {@code\n * {key}} or {@code {{key}}}. The core {@code key} is extracted from whatever is between the\n * innermost pair of braces after trimming whitespace and possibly removing the {@code ?} which\n * denotes optionality (e.g. {@code {key?}}). The {@code key} itself must not contain curly\n * braces. For typical usage, a single pair of braces like {@code {my_variable}} is standard.\n *\n *

The extracted {@code key} determines the source and name of the value:\n *\n *

    \n *
  • Session State Variables: The {@code key} (e.g., {@code \"variable_name\"} or {@code\n * \"prefix:variable_name\"}) refers to a variable in session state.\n *
      \n *
    • Simple name: {@code {variable_name}}. The {@code variable_name} part must be a\n * valid identifier as per {@link #isValidStateName(String)}. Invalid names will\n * result in the placeholder being returned as is.\n *
    • Prefixed name: {@code {prefix:variable_name}}. Valid prefixes are: {@value\n * com.google.adk.sessions.State#APP_PREFIX}, {@value\n * com.google.adk.sessions.State#USER_PREFIX}, and {@value\n * com.google.adk.sessions.State#TEMP_PREFIX} The part of the name following the\n * prefix must also be a valid identifier. Invalid prefixes will result in the\n * placeholder being returned as is.\n *
    \n *
  • Artifacts: The {@code key} starts with \"{@code artifact.}\" (e.g., {@code\n * \"artifact.file_name\"}).\n *
  • Optional Placeholders: A {@code key} can be marked as optional by appending a\n * question mark {@code ?} at its very end, inside the braces.\n *
      \n *
    • Example: {@code {optional_variable?}}, {@code {{artifact.optional_file.txt?}}}\n *
    • If an optional placeholder cannot be resolved (e.g., variable not found, artifact\n * not found), it is replaced with an empty string.\n *
    \n *
\n *\n * Example Usage:\n *\n *
{@code\n   * InvocationContext context = ...; // Assume this is initialized with session and artifact service\n   * Session session = context.session();\n   *\n   * session.state().put(\"user:name\", \"Alice\");\n   *\n   * context.artifactService().saveArtifact(\n   *     session.appName(), session.userId(), session.id(), \"knowledge.txt\", Part.fromText(\"Origins of the universe: At first, there was-\"));\n   *\n   * String template = \"You are {user:name}'s assistant. Answer questions based on your knowledge. Your knowledge: {artifact.knowledge.txt}.\" +\n   *                   \" Your extra knowledge: {artifact.missing_artifact.txt?}\";\n   *\n   * Single populatedStringSingle = InstructionUtils.injectSessionState(context, template);\n   * populatedStringSingle.subscribe(\n   *     result -> System.out.println(result),\n   *     // Expected: \"You are Alice's assistant. Answer questions based on your knowledge. Your knowledge: Origins of the universe: At first, there was-. Your extra knowledge: \"\n   *     error -> System.err.println(\"Error populating template: \" + error.getMessage())\n   * );\n   * }
\n *\n * @param context The invocation context providing access to session state and artifact services.\n * @param template The instruction template string containing placeholders to be populated.\n * @return A {@link Single} that will emit the populated instruction string upon successful\n * resolution of all non-optional placeholders. Emits the original template if it is empty or\n * contains no placeholders that are processed.\n * @throws NullPointerException if the template or context is null.\n * @throws IllegalArgumentException if a non-optional variable or artifact is not found.\n */\n public static Single injectSessionState(InvocationContext context, String template) {\n if (template == null) {\n return Single.error(new NullPointerException(\"template cannot be null\"));\n }\n if (context == null) {\n return Single.error(new NullPointerException(\"context cannot be null\"));\n }\n Matcher matcher = INSTRUCTION_PLACEHOLDER_PATTERN.matcher(template);\n List> parts = new ArrayList<>();\n int lastEnd = 0;\n\n while (matcher.find()) {\n if (matcher.start() > lastEnd) {\n parts.add(Single.just(template.substring(lastEnd, matcher.start())));\n }\n MatchResult matchResult = matcher.toMatchResult();\n parts.add(resolveMatchAsync(context, matchResult));\n lastEnd = matcher.end();\n }\n if (lastEnd < template.length()) {\n parts.add(Single.just(template.substring(lastEnd)));\n }\n\n if (parts.isEmpty()) {\n return Single.just(template);\n }\n\n return Single.zip(\n parts,\n objects -> {\n StringBuilder sb = new StringBuilder();\n for (Object obj : objects) {\n sb.append(obj);\n }\n return sb.toString();\n });\n }\n\n private static Single resolveMatchAsync(InvocationContext context, MatchResult match) {\n String placeholder = match.group();\n String varNameFromPlaceholder =\n placeholder.replaceAll(\"^\\\\{+\", \"\").replaceAll(\"\\\\}+$\", \"\").trim();\n\n final boolean optional;\n final String cleanVarName;\n if (varNameFromPlaceholder.endsWith(\"?\")) {\n optional = true;\n cleanVarName = varNameFromPlaceholder.substring(0, varNameFromPlaceholder.length() - 1);\n } else {\n optional = false;\n cleanVarName = varNameFromPlaceholder;\n }\n\n if (cleanVarName.startsWith(\"artifact.\")) {\n final String artifactName = cleanVarName.substring(\"artifact.\".length());\n Session session = context.session();\n\n Maybe artifactMaybe =\n context\n .artifactService()\n .loadArtifact(\n session.appName(),\n session.userId(),\n session.id(),\n artifactName,\n Optional.empty());\n\n return artifactMaybe\n .map(Part::toJson)\n .switchIfEmpty(\n Single.defer(\n () -> {\n if (optional) {\n return Single.just(\"\");\n } else {\n return Single.error(\n new IllegalArgumentException(\n String.format(\"Artifact %s not found.\", artifactName)));\n }\n }));\n\n } else if (!isValidStateName(cleanVarName)) {\n return Single.just(placeholder);\n } else if (context.session().state().containsKey(cleanVarName)) {\n Object value = context.session().state().get(cleanVarName);\n return Single.just(String.valueOf(value));\n } else if (optional) {\n return Single.just(\"\");\n } else {\n return Single.error(\n new IllegalArgumentException(\n String.format(\"Context variable not found: `%s`.\", cleanVarName)));\n }\n }\n\n /**\n * Checks if a given string is a valid state variable name.\n *\n *

A valid state variable name must either:\n *\n *

    \n *
  • Be a valid identifier (as defined by {@link Character#isJavaIdentifierStart(int)} and\n * {@link Character#isJavaIdentifierPart(int)}).\n *
  • Start with a valid prefix ({@value com.google.adk.sessions.State#APP_PREFIX}, {@value\n * com.google.adk.sessions.State#USER_PREFIX}, or {@value\n * com.google.adk.sessions.State#TEMP_PREFIX}) followed by a valid identifier.\n *
\n *\n * @param varName The string to check.\n * @return True if the string is a valid state variable name, false otherwise.\n */\n private static boolean isValidStateName(String varName) {\n if (varName.isEmpty()) {\n return false;\n }\n String[] parts = varName.split(\":\", 2);\n if (parts.length == 1) {\n return isValidIdentifier(parts[0]);\n }\n\n if (parts.length == 2) {\n String prefixPart = parts[0] + \":\";\n ImmutableSet validPrefixes =\n ImmutableSet.of(State.APP_PREFIX, State.USER_PREFIX, State.TEMP_PREFIX);\n if (validPrefixes.contains(prefixPart)) {\n return isValidIdentifier(parts[1]);\n }\n }\n return false;\n }\n\n private static boolean isValidIdentifier(String s) {\n if (s.isEmpty()) {\n return false;\n }\n if (!Character.isJavaIdentifierStart(s.charAt(0))) {\n return false;\n }\n for (int i = 1; i < s.length(); i++) {\n if (!Character.isJavaIdentifierPart(s.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/BuiltInCodeExecutionTool.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools;\n\nimport com.google.adk.models.LlmRequest;\nimport com.google.common.collect.ImmutableList;\nimport com.google.genai.types.GenerateContentConfig;\nimport com.google.genai.types.Tool;\nimport com.google.genai.types.ToolCodeExecution;\nimport io.reactivex.rxjava3.core.Completable;\nimport java.util.List;\n\n/**\n * A built-in code execution tool that is automatically invoked by Gemini 2 models.\n *\n *

This tool operates internally within the model and does not require or perform local code\n * execution.\n */\npublic final class BuiltInCodeExecutionTool extends BaseTool {\n\n public BuiltInCodeExecutionTool() {\n super(\"code_execution\", \"code_execution\");\n }\n\n @Override\n public Completable processLlmRequest(\n LlmRequest.Builder llmRequestBuilder, ToolContext toolContext) {\n\n String model = llmRequestBuilder.build().model().get();\n if (model.isEmpty() || !model.startsWith(\"gemini-2\")) {\n return Completable.error(\n new IllegalArgumentException(\"Code execution tool is not supported for model \" + model));\n }\n GenerateContentConfig.Builder configBuilder =\n llmRequestBuilder\n .build()\n .config()\n .map(GenerateContentConfig::toBuilder)\n .orElse(GenerateContentConfig.builder());\n\n List existingTools = configBuilder.build().tools().orElse(ImmutableList.of());\n ImmutableList.Builder updatedToolsBuilder = ImmutableList.builder();\n updatedToolsBuilder\n .addAll(existingTools)\n .add(Tool.builder().codeExecution(ToolCodeExecution.builder().build()).build());\n configBuilder.tools(updatedToolsBuilder.build());\n llmRequestBuilder.config(configBuilder.build());\n return Completable.complete();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/sessions/HttpApiClient.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\nimport com.google.auth.oauth2.GoogleCredentials;\nimport com.google.common.base.Ascii;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.genai.errors.GenAiIOException;\nimport com.google.genai.types.HttpOptions;\nimport java.io.IOException;\nimport java.util.Map;\nimport java.util.Optional;\nimport okhttp3.MediaType;\nimport okhttp3.Request;\nimport okhttp3.RequestBody;\nimport okhttp3.Response;\n\n/** Base client for the HTTP APIs. */\npublic class HttpApiClient extends ApiClient {\n public static final MediaType MEDIA_TYPE_APPLICATION_JSON =\n MediaType.parse(\"application/json; charset=utf-8\");\n\n /** Constructs an ApiClient for Google AI APIs. */\n HttpApiClient(Optional apiKey, Optional httpOptions) {\n super(apiKey, httpOptions);\n }\n\n /** Constructs an ApiClient for Vertex AI APIs. */\n HttpApiClient(\n Optional project,\n Optional location,\n Optional credentials,\n Optional httpOptions) {\n super(project, location, credentials, httpOptions);\n }\n\n /** Sends a Http request given the http method, path, and request json string. */\n @Override\n public ApiResponse request(String httpMethod, String path, String requestJson) {\n boolean queryBaseModel =\n Ascii.equalsIgnoreCase(httpMethod, \"GET\") && path.startsWith(\"publishers/google/models/\");\n if (this.vertexAI() && !path.startsWith(\"projects/\") && !queryBaseModel) {\n path =\n String.format(\"projects/%s/locations/%s/\", this.project.get(), this.location.get())\n + path;\n }\n String requestUrl =\n String.format(\n \"%s/%s/%s\", httpOptions.baseUrl().get(), httpOptions.apiVersion().get(), path);\n\n Request.Builder requestBuilder = new Request.Builder().url(requestUrl);\n setHeaders(requestBuilder);\n\n if (Ascii.equalsIgnoreCase(httpMethod, \"POST\")) {\n requestBuilder.post(RequestBody.create(MEDIA_TYPE_APPLICATION_JSON, requestJson));\n\n } else if (Ascii.equalsIgnoreCase(httpMethod, \"GET\")) {\n requestBuilder.get();\n } else if (Ascii.equalsIgnoreCase(httpMethod, \"DELETE\")) {\n requestBuilder.delete();\n } else {\n throw new IllegalArgumentException(\"Unsupported HTTP method: \" + httpMethod);\n }\n return executeRequest(requestBuilder.build());\n }\n\n /** Sets the required headers (including auth) on the request object. */\n private void setHeaders(Request.Builder requestBuilder) {\n for (Map.Entry header :\n httpOptions.headers().orElse(ImmutableMap.of()).entrySet()) {\n requestBuilder.header(header.getKey(), header.getValue());\n }\n\n if (apiKey.isPresent()) {\n requestBuilder.header(\"x-goog-api-key\", apiKey.get());\n } else {\n GoogleCredentials cred =\n credentials.orElseThrow(() -> new IllegalStateException(\"credentials is required\"));\n try {\n cred.refreshIfExpired();\n } catch (IOException e) {\n throw new GenAiIOException(\"Failed to refresh credentials.\", e);\n }\n String accessToken;\n try {\n accessToken = cred.getAccessToken().getTokenValue();\n } catch (NullPointerException e) {\n // For test cases where the access token is not available.\n if (e.getMessage()\n .contains(\n \"because the return value of\"\n + \" \\\"com.google.auth.oauth2.GoogleCredentials.getAccessToken()\\\" is null\")) {\n accessToken = \"\";\n } else {\n throw e;\n }\n }\n requestBuilder.header(\"Authorization\", \"Bearer \" + accessToken);\n\n if (cred.getQuotaProjectId() != null) {\n requestBuilder.header(\"x-goog-user-project\", cred.getQuotaProjectId());\n }\n }\n }\n\n /** Executes the given HTTP request. */\n private ApiResponse executeRequest(Request request) {\n try {\n Response response = httpClient.newCall(request).execute();\n return new HttpApiResponse(response);\n } catch (IOException e) {\n throw new GenAiIOException(\"Failed to execute HTTP request.\", e);\n }\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/llmflows/Basic.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows.llmflows;\n\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.agents.LlmAgent;\nimport com.google.adk.models.LlmRequest;\nimport com.google.common.collect.ImmutableList;\nimport com.google.genai.types.GenerateContentConfig;\nimport com.google.genai.types.LiveConnectConfig;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.Optional;\n\n/** {@link RequestProcessor} that handles basic information to build the LLM request. */\npublic final class Basic implements RequestProcessor {\n\n public Basic() {}\n\n @Override\n public Single processRequest(\n InvocationContext context, LlmRequest request) {\n if (!(context.agent() instanceof LlmAgent)) {\n throw new IllegalArgumentException(\"Agent in InvocationContext is not an instance of Agent.\");\n }\n LlmAgent agent = (LlmAgent) context.agent();\n String modelName =\n agent.resolvedModel().model().isPresent()\n ? agent.resolvedModel().model().get().model()\n : agent.resolvedModel().modelName().get();\n\n LiveConnectConfig.Builder liveConnectConfigBuilder =\n LiveConnectConfig.builder().responseModalities(context.runConfig().responseModalities());\n Optional.ofNullable(context.runConfig().speechConfig())\n .ifPresent(liveConnectConfigBuilder::speechConfig);\n Optional.ofNullable(context.runConfig().outputAudioTranscription())\n .ifPresent(liveConnectConfigBuilder::outputAudioTranscription);\n\n LlmRequest.Builder builder =\n request.toBuilder()\n .model(modelName)\n .config(agent.generateContentConfig().orElse(GenerateContentConfig.builder().build()))\n .liveConnectConfig(liveConnectConfigBuilder.build());\n\n agent.outputSchema().ifPresent(builder::outputSchema);\n return Single.just(\n RequestProcessor.RequestProcessingResult.create(builder.build(), ImmutableList.of()));\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/mcp/McpToolset.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools.mcp;\n\nimport static com.google.common.collect.ImmutableList.toImmutableList;\n\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.google.adk.JsonBaseModel;\nimport com.google.adk.agents.ReadonlyContext;\nimport com.google.adk.tools.BaseTool;\nimport com.google.adk.tools.BaseToolset;\nimport io.modelcontextprotocol.client.McpSyncClient;\nimport io.modelcontextprotocol.client.transport.ServerParameters;\nimport io.modelcontextprotocol.spec.McpSchema.ListToolsResult;\nimport io.reactivex.rxjava3.core.Flowable;\nimport java.util.Objects;\nimport java.util.Optional;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * Connects to a MCP Server, and retrieves MCP Tools into ADK Tools.\n *\n *

Attributes:\n *\n *

    \n *
  • {@code connectionParams}: The connection parameters to the MCP server. Can be either {@code\n * ServerParameters} or {@code SseServerParameters}.\n *
  • {@code session}: The MCP session being initialized with the connection.\n *
\n */\npublic class McpToolset implements BaseToolset {\n private static final Logger logger = LoggerFactory.getLogger(McpToolset.class);\n private final McpSessionManager mcpSessionManager;\n private McpSyncClient mcpSession;\n private final ObjectMapper objectMapper;\n private final Optional toolFilter;\n\n private static final int MAX_RETRIES = 3;\n private static final long RETRY_DELAY_MILLIS = 100;\n\n /**\n * Initializes the McpToolset with SSE server parameters.\n *\n * @param connectionParams The SSE connection parameters to the MCP server.\n * @param objectMapper An ObjectMapper instance for parsing schemas.\n * @param toolFilter An Optional containing either a ToolPredicate or a List of tool names.\n */\n public McpToolset(\n SseServerParameters connectionParams,\n ObjectMapper objectMapper,\n Optional toolFilter) {\n Objects.requireNonNull(connectionParams);\n Objects.requireNonNull(objectMapper);\n this.objectMapper = objectMapper;\n this.mcpSessionManager = new McpSessionManager(connectionParams);\n this.toolFilter = toolFilter;\n }\n\n /**\n * Initializes the McpToolset with SSE server parameters and no tool filter.\n *\n * @param connectionParams The SSE connection parameters to the MCP server.\n * @param objectMapper An ObjectMapper instance for parsing schemas.\n */\n public McpToolset(SseServerParameters connectionParams, ObjectMapper objectMapper) {\n this(connectionParams, objectMapper, Optional.empty());\n }\n\n /**\n * Initializes the McpToolset with local server parameters.\n *\n * @param connectionParams The local server connection parameters to the MCP server.\n * @param objectMapper An ObjectMapper instance for parsing schemas.\n * @param toolFilter An Optional containing either a ToolPredicate or a List of tool names.\n */\n public McpToolset(\n ServerParameters connectionParams, ObjectMapper objectMapper, Optional toolFilter) {\n Objects.requireNonNull(connectionParams);\n Objects.requireNonNull(objectMapper);\n this.objectMapper = objectMapper;\n this.mcpSessionManager = new McpSessionManager(connectionParams);\n this.toolFilter = toolFilter;\n }\n\n /**\n * Initializes the McpToolset with local server parameters and no tool filter.\n *\n * @param connectionParams The local server connection parameters to the MCP server.\n * @param objectMapper An ObjectMapper instance for parsing schemas.\n */\n public McpToolset(ServerParameters connectionParams, ObjectMapper objectMapper) {\n this(connectionParams, objectMapper, Optional.empty());\n }\n\n /**\n * Initializes the McpToolset with SSE server parameters, using the ObjectMapper used across the\n * ADK.\n *\n * @param connectionParams The SSE connection parameters to the MCP server.\n * @param toolFilter An Optional containing either a ToolPredicate or a List of tool names.\n */\n public McpToolset(SseServerParameters connectionParams, Optional toolFilter) {\n this(connectionParams, JsonBaseModel.getMapper(), toolFilter);\n }\n\n /**\n * Initializes the McpToolset with SSE server parameters, using the ObjectMapper used across the\n * ADK and no tool filter.\n *\n * @param connectionParams The SSE connection parameters to the MCP server.\n */\n public McpToolset(SseServerParameters connectionParams) {\n this(connectionParams, JsonBaseModel.getMapper(), Optional.empty());\n }\n\n /**\n * Initializes the McpToolset with local server parameters, using the ObjectMapper used across the\n * ADK.\n *\n * @param connectionParams The local server connection parameters to the MCP server.\n * @param toolFilter An Optional containing either a ToolPredicate or a List of tool names.\n */\n public McpToolset(ServerParameters connectionParams, Optional toolFilter) {\n this(connectionParams, JsonBaseModel.getMapper(), toolFilter);\n }\n\n /**\n * Initializes the McpToolset with local server parameters, using the ObjectMapper used across the\n * ADK and no tool filter.\n *\n * @param connectionParams The local server connection parameters to the MCP server.\n */\n public McpToolset(ServerParameters connectionParams) {\n this(connectionParams, JsonBaseModel.getMapper(), Optional.empty());\n }\n\n @Override\n public Flowable getTools(ReadonlyContext readonlyContext) {\n return Flowable.fromCallable(\n () -> {\n for (int i = 0; i < MAX_RETRIES; i++) {\n try {\n if (this.mcpSession == null) {\n logger.info(\"MCP session is null or closed, initializing (attempt {}).\", i + 1);\n this.mcpSession = this.mcpSessionManager.createSession();\n }\n\n ListToolsResult toolsResponse = this.mcpSession.listTools();\n return toolsResponse.tools().stream()\n .map(\n tool ->\n new McpTool(\n tool, this.mcpSession, this.mcpSessionManager, this.objectMapper))\n .filter(\n tool ->\n isToolSelected(\n tool, toolFilter, Optional.ofNullable(readonlyContext)))\n .collect(toImmutableList());\n } catch (IllegalArgumentException e) {\n // This could happen if parameters for tool loading are somehow invalid.\n // This is likely a fatal error and should not be retried.\n logger.error(\"Invalid argument encountered during tool loading.\", e);\n throw new McpToolLoadingException(\n \"Invalid argument encountered during tool loading.\", e);\n } catch (RuntimeException e) { // Catch any other unexpected runtime exceptions\n logger.error(\"Unexpected error during tool loading, retry attempt \" + (i + 1), e);\n if (i < MAX_RETRIES - 1) {\n // For other general exceptions, we might still want to retry if they are\n // potentially transient, or if we don't have more specific handling. But it's\n // better to be specific. For now, we'll treat them as potentially retryable but\n // log\n // them at a higher level.\n try {\n logger.info(\n \"Reinitializing MCP session before next retry for unexpected error.\");\n this.mcpSession = this.mcpSessionManager.createSession();\n Thread.sleep(RETRY_DELAY_MILLIS);\n } catch (InterruptedException ie) {\n Thread.currentThread().interrupt();\n logger.error(\n \"Interrupted during retry delay for loadTools (unexpected error).\", ie);\n throw new McpToolLoadingException(\n \"Interrupted during retry delay (unexpected error)\", ie);\n } catch (RuntimeException reinitE) {\n logger.error(\n \"Failed to reinitialize session during retry (unexpected error).\",\n reinitE);\n throw new McpInitializationException(\n \"Failed to reinitialize session during tool loading retry (unexpected\"\n + \" error).\",\n reinitE);\n }\n } else {\n logger.error(\n \"Failed to load tools after multiple retries due to unexpected error.\", e);\n throw new McpToolLoadingException(\n \"Failed to load tools after multiple retries due to unexpected error.\", e);\n }\n }\n }\n // This line should ideally not be reached if retries are handled correctly or an\n // exception is always thrown.\n throw new IllegalStateException(\"Unexpected state in getTools retry loop\");\n })\n .flatMapIterable(tools -> tools);\n }\n\n @Override\n public void close() {\n if (this.mcpSession != null) {\n try {\n this.mcpSession.close();\n logger.debug(\"MCP session closed successfully.\");\n } catch (RuntimeException e) {\n logger.error(\"Failed to close MCP session\", e);\n // We don't throw an exception here, as closing is a cleanup operation and\n // failing to close shouldn't prevent the program from continuing (or exiting).\n // However, we log the error for debugging purposes.\n } finally {\n this.mcpSession = null;\n }\n }\n }\n\n /** Base exception for all errors originating from {@code McpToolset}. */\n public static class McpToolsetException extends RuntimeException {\n public McpToolsetException(String message, Throwable cause) {\n super(message, cause);\n }\n }\n\n /** Exception thrown when there's an error during MCP session initialization. */\n public static class McpInitializationException extends McpToolsetException {\n public McpInitializationException(String message, Throwable cause) {\n super(message, cause);\n }\n }\n\n /** Exception thrown when there's an error during loading tools from the MCP server. */\n public static class McpToolLoadingException extends McpToolsetException {\n public McpToolLoadingException(String message, Throwable cause) {\n super(message, cause);\n }\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/applicationintegrationtoolset/IntegrationConnectorTool.java", "package com.google.adk.tools.applicationintegrationtoolset;\n\nimport static com.google.common.base.Strings.isNullOrEmpty;\nimport static java.nio.charset.StandardCharsets.UTF_8;\n\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.fasterxml.jackson.databind.node.ArrayNode;\nimport com.fasterxml.jackson.databind.node.ObjectNode;\nimport com.google.adk.tools.BaseTool;\nimport com.google.adk.tools.ToolContext;\nimport com.google.auth.oauth2.GoogleCredentials;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Streams;\nimport com.google.genai.types.FunctionDeclaration;\nimport com.google.genai.types.Schema;\nimport io.reactivex.rxjava3.core.Single;\nimport java.io.ByteArrayInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\nimport org.jspecify.annotations.Nullable;\n\n/** Application Integration Tool */\npublic class IntegrationConnectorTool extends BaseTool {\n\n private final String openApiSpec;\n private final String pathUrl;\n private final HttpExecutor httpExecutor;\n private final String connectionName;\n private final String serviceName;\n private final String host;\n private String entity;\n private String operation;\n private String action;\n private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();\n\n interface HttpExecutor {\n HttpResponse send(HttpRequest request, HttpResponse.BodyHandler responseBodyHandler)\n throws IOException, InterruptedException;\n\n String getToken() throws IOException;\n\n public HttpExecutor createExecutor(String serviceAccountJson);\n }\n\n static class DefaultHttpExecutor implements HttpExecutor {\n private final HttpClient client = HttpClient.newHttpClient();\n private final String serviceAccountJson;\n\n /** Default constructor for when no service account is specified. */\n DefaultHttpExecutor() {\n this(null);\n }\n\n /**\n * Constructor that accepts an optional service account JSON string.\n *\n * @param serviceAccountJson The service account key as a JSON string, or null.\n */\n DefaultHttpExecutor(@Nullable String serviceAccountJson) {\n this.serviceAccountJson = serviceAccountJson;\n }\n\n @Override\n public HttpResponse send(\n HttpRequest request, HttpResponse.BodyHandler responseBodyHandler)\n throws IOException, InterruptedException {\n return client.send(request, responseBodyHandler);\n }\n\n @Override\n public String getToken() throws IOException {\n GoogleCredentials credentials;\n\n if (this.serviceAccountJson != null && !this.serviceAccountJson.trim().isEmpty()) {\n try (InputStream is = new ByteArrayInputStream(this.serviceAccountJson.getBytes(UTF_8))) {\n credentials =\n GoogleCredentials.fromStream(is)\n .createScoped(\"https://www.googleapis.com/auth/cloud-platform\");\n } catch (IOException e) {\n throw new IOException(\"Failed to load credentials from service_account_json.\", e);\n }\n } else {\n try {\n credentials =\n GoogleCredentials.getApplicationDefault()\n .createScoped(\"https://www.googleapis.com/auth/cloud-platform\");\n } catch (IOException e) {\n throw new IOException(\n \"Please provide a service account or configure Application Default Credentials. To\"\n + \" set up ADC, see\"\n + \" https://cloud.google.com/docs/authentication/external/set-up-adc.\",\n e);\n }\n }\n\n credentials.refreshIfExpired();\n return credentials.getAccessToken().getTokenValue();\n }\n\n @Override\n public HttpExecutor createExecutor(String serviceAccountJson) {\n if (isNullOrEmpty(serviceAccountJson)) {\n return new DefaultHttpExecutor();\n } else {\n return new DefaultHttpExecutor(serviceAccountJson);\n }\n }\n }\n\n private static final ImmutableList EXCLUDE_FIELDS =\n ImmutableList.of(\"connectionName\", \"serviceName\", \"host\", \"entity\", \"operation\", \"action\");\n\n private static final ImmutableList OPTIONAL_FIELDS =\n ImmutableList.of(\"pageSize\", \"pageToken\", \"filter\", \"sortByColumns\");\n\n /** Constructor for Application Integration Tool for integration */\n IntegrationConnectorTool(\n String openApiSpec,\n String pathUrl,\n String toolName,\n String toolDescription,\n String serviceAccountJson) {\n this(\n openApiSpec,\n pathUrl,\n toolName,\n toolDescription,\n null,\n null,\n null,\n serviceAccountJson,\n new DefaultHttpExecutor().createExecutor(serviceAccountJson));\n }\n\n /**\n * Constructor for Application Integration Tool with connection name, service name, host, entity,\n * operation, and action\n */\n IntegrationConnectorTool(\n String openApiSpec,\n String pathUrl,\n String toolName,\n String toolDescription,\n String connectionName,\n String serviceName,\n String host,\n String serviceAccountJson) {\n this(\n openApiSpec,\n pathUrl,\n toolName,\n toolDescription,\n connectionName,\n serviceName,\n host,\n serviceAccountJson,\n new DefaultHttpExecutor().createExecutor(serviceAccountJson));\n }\n\n IntegrationConnectorTool(\n String openApiSpec,\n String pathUrl,\n String toolName,\n String toolDescription,\n @Nullable String connectionName,\n @Nullable String serviceName,\n @Nullable String host,\n @Nullable String serviceAccountJson,\n HttpExecutor httpExecutor) {\n super(toolName, toolDescription);\n this.openApiSpec = openApiSpec;\n this.pathUrl = pathUrl;\n this.connectionName = connectionName;\n this.serviceName = serviceName;\n this.host = host;\n this.httpExecutor = httpExecutor;\n }\n\n Schema toGeminiSchema(String openApiSchema, String operationId) throws Exception {\n String resolvedSchemaString = getResolvedRequestSchemaByOperationId(openApiSchema, operationId);\n return Schema.fromJson(resolvedSchemaString);\n }\n\n @Override\n public Optional declaration() {\n try {\n String operationId = getOperationIdFromPathUrl(openApiSpec, pathUrl);\n Schema parametersSchema = toGeminiSchema(openApiSpec, operationId);\n String operationDescription = getOperationDescription(openApiSpec, operationId);\n\n FunctionDeclaration declaration =\n FunctionDeclaration.builder()\n .name(operationId)\n .description(operationDescription)\n .parameters(parametersSchema)\n .build();\n return Optional.of(declaration);\n } catch (Exception e) {\n System.err.println(\"Failed to get OpenAPI spec: \" + e.getMessage());\n return Optional.empty();\n }\n }\n\n @Override\n public Single> runAsync(Map args, ToolContext toolContext) {\n if (this.connectionName != null) {\n args.put(\"connectionName\", this.connectionName);\n args.put(\"serviceName\", this.serviceName);\n args.put(\"host\", this.host);\n if (!isNullOrEmpty(this.entity)) {\n args.put(\"entity\", this.entity);\n } else if (!isNullOrEmpty(this.action)) {\n args.put(\"action\", this.action);\n }\n if (!isNullOrEmpty(this.operation)) {\n args.put(\"operation\", this.operation);\n }\n }\n\n return Single.fromCallable(\n () -> {\n try {\n String response = executeIntegration(args);\n return ImmutableMap.of(\"result\", response);\n } catch (Exception e) {\n System.err.println(\"Failed to execute integration: \" + e.getMessage());\n return ImmutableMap.of(\"error\", e.getMessage());\n }\n });\n }\n\n private String executeIntegration(Map args) throws Exception {\n String url = String.format(\"https://integrations.googleapis.com%s\", this.pathUrl);\n String jsonRequestBody;\n try {\n jsonRequestBody = OBJECT_MAPPER.writeValueAsString(args);\n } catch (IOException e) {\n throw new Exception(\"Error converting args to JSON: \" + e.getMessage(), e);\n }\n HttpRequest request =\n HttpRequest.newBuilder()\n .uri(URI.create(url))\n .header(\"Authorization\", \"Bearer \" + httpExecutor.getToken())\n .header(\"Content-Type\", \"application/json\")\n .POST(HttpRequest.BodyPublishers.ofString(jsonRequestBody))\n .build();\n HttpResponse response =\n httpExecutor.send(request, HttpResponse.BodyHandlers.ofString());\n\n if (response.statusCode() < 200 || response.statusCode() >= 300) {\n throw new Exception(\n \"Error executing integration. Status: \"\n + response.statusCode()\n + \" , Response: \"\n + response.body());\n }\n return response.body();\n }\n\n String getOperationIdFromPathUrl(String openApiSchemaString, String pathUrl) throws Exception {\n JsonNode topLevelNode = OBJECT_MAPPER.readTree(openApiSchemaString);\n JsonNode specNode = topLevelNode.path(\"openApiSpec\");\n if (specNode.isMissingNode() || !specNode.isTextual()) {\n throw new IllegalArgumentException(\n \"Failed to get OpenApiSpec, please check the project and region for the integration.\");\n }\n JsonNode rootNode = OBJECT_MAPPER.readTree(specNode.asText());\n JsonNode paths = rootNode.path(\"paths\");\n\n // Iterate through each path in the OpenAPI spec.\n Iterator> pathsFields = paths.fields();\n while (pathsFields.hasNext()) {\n Map.Entry pathEntry = pathsFields.next();\n String currentPath = pathEntry.getKey();\n if (!currentPath.equals(pathUrl)) {\n continue;\n }\n JsonNode pathItem = pathEntry.getValue();\n\n Iterator> methods = pathItem.fields();\n while (methods.hasNext()) {\n Map.Entry methodEntry = methods.next();\n JsonNode operationNode = methodEntry.getValue();\n // Set values for entity, operation, and action\n this.entity = \"\";\n this.operation = \"\";\n this.action = \"\";\n if (operationNode.has(\"x-entity\")) {\n this.entity = operationNode.path(\"x-entity\").asText();\n } else if (operationNode.has(\"x-action\")) {\n this.action = operationNode.path(\"x-action\").asText();\n }\n if (operationNode.has(\"x-operation\")) {\n this.operation = operationNode.path(\"x-operation\").asText();\n }\n // Get the operationId from the operationNode\n if (operationNode.has(\"operationId\")) {\n return operationNode.path(\"operationId\").asText();\n }\n }\n }\n throw new Exception(\"Could not find operationId for pathUrl: \" + pathUrl);\n }\n\n private String getResolvedRequestSchemaByOperationId(\n String openApiSchemaString, String operationId) throws Exception {\n JsonNode topLevelNode = OBJECT_MAPPER.readTree(openApiSchemaString);\n JsonNode specNode = topLevelNode.path(\"openApiSpec\");\n if (specNode.isMissingNode() || !specNode.isTextual()) {\n throw new IllegalArgumentException(\n \"Failed to get OpenApiSpec, please check the project and region for the integration.\");\n }\n JsonNode rootNode = OBJECT_MAPPER.readTree(specNode.asText());\n JsonNode operationNode = findOperationNodeById(rootNode, operationId);\n if (operationNode == null) {\n throw new Exception(\"Could not find operation with operationId: \" + operationId);\n }\n JsonNode requestSchemaNode =\n operationNode.path(\"requestBody\").path(\"content\").path(\"application/json\").path(\"schema\");\n\n if (requestSchemaNode.isMissingNode()) {\n throw new Exception(\"Could not find request body schema for operationId: \" + operationId);\n }\n\n JsonNode resolvedSchema = resolveRefs(requestSchemaNode, rootNode);\n\n if (resolvedSchema.isObject()) {\n ObjectNode schemaObject = (ObjectNode) resolvedSchema;\n\n // 1. Remove excluded fields from the 'properties' object.\n JsonNode propertiesNode = schemaObject.path(\"properties\");\n if (propertiesNode.isObject()) {\n ObjectNode propertiesObject = (ObjectNode) propertiesNode;\n for (String field : EXCLUDE_FIELDS) {\n propertiesObject.remove(field);\n }\n }\n\n // 2. Remove optional and excluded fields from the 'required' array.\n JsonNode requiredNode = schemaObject.path(\"required\");\n if (requiredNode.isArray()) {\n // Combine the lists of fields to remove\n List fieldsToRemove =\n Streams.concat(OPTIONAL_FIELDS.stream(), EXCLUDE_FIELDS.stream()).toList();\n\n // To safely remove items from a list while iterating, we must use an Iterator.\n ArrayNode requiredArray = (ArrayNode) requiredNode;\n Iterator elements = requiredArray.elements();\n while (elements.hasNext()) {\n JsonNode element = elements.next();\n if (element.isTextual() && fieldsToRemove.contains(element.asText())) {\n // This removes the current element from the underlying array.\n elements.remove();\n }\n }\n }\n }\n return OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(resolvedSchema);\n }\n\n private @Nullable JsonNode findOperationNodeById(JsonNode rootNode, String operationId) {\n JsonNode paths = rootNode.path(\"paths\");\n for (JsonNode pathItem : paths) {\n Iterator> methods = pathItem.fields();\n while (methods.hasNext()) {\n Map.Entry methodEntry = methods.next();\n JsonNode operationNode = methodEntry.getValue();\n if (operationNode.path(\"operationId\").asText().equals(operationId)) {\n return operationNode;\n }\n }\n }\n return null;\n }\n\n private JsonNode resolveRefs(JsonNode currentNode, JsonNode rootNode) {\n if (currentNode.isObject()) {\n ObjectNode objectNode = (ObjectNode) currentNode;\n if (objectNode.has(\"$ref\")) {\n String refPath = objectNode.get(\"$ref\").asText();\n if (refPath.isEmpty() || !refPath.startsWith(\"#/\")) {\n return objectNode;\n }\n JsonNode referencedNode = rootNode.at(refPath.substring(1));\n if (referencedNode.isMissingNode()) {\n return objectNode;\n }\n return resolveRefs(referencedNode, rootNode);\n } else {\n ObjectNode newObjectNode = OBJECT_MAPPER.createObjectNode();\n Iterator> fields = currentNode.fields();\n while (fields.hasNext()) {\n Map.Entry field = fields.next();\n newObjectNode.set(field.getKey(), resolveRefs(field.getValue(), rootNode));\n }\n return newObjectNode;\n }\n }\n return currentNode;\n }\n\n private String getOperationDescription(String openApiSchemaString, String operationId)\n throws Exception {\n JsonNode topLevelNode = OBJECT_MAPPER.readTree(openApiSchemaString);\n JsonNode specNode = topLevelNode.path(\"openApiSpec\");\n if (specNode.isMissingNode() || !specNode.isTextual()) {\n return \"\";\n }\n JsonNode rootNode = OBJECT_MAPPER.readTree(specNode.asText());\n JsonNode operationNode = findOperationNodeById(rootNode, operationId);\n if (operationNode == null) {\n return \"\";\n }\n return operationNode.path(\"summary\").asText();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/models/LlmRegistry.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.models;\n\nimport java.util.Map;\nimport java.util.concurrent.ConcurrentHashMap;\n\n/** Central registry for managing Large Language Model (LLM) instances. */\npublic final class LlmRegistry {\n\n /** A thread-safe cache mapping model names to LLM instances. */\n private static final Map instances = new ConcurrentHashMap<>();\n\n /** The factory interface for creating LLM instances. */\n @FunctionalInterface\n public interface LlmFactory {\n BaseLlm create(String modelName);\n }\n\n /** Map of model name patterns regex to factories. */\n private static final Map llmFactories = new ConcurrentHashMap<>();\n\n /** Registers default LLM factories, e.g. for Gemini models. */\n static {\n registerLlm(\"gemini-.*\", modelName -> Gemini.builder().modelName(modelName).build());\n }\n\n /**\n * Registers a factory for model names matching the given regex pattern.\n *\n * @param modelNamePattern Regex pattern for matching model names.\n * @param factory Factory to create LLM instances.\n */\n public static void registerLlm(String modelNamePattern, LlmFactory factory) {\n llmFactories.put(modelNamePattern, factory);\n }\n\n /**\n * Returns an LLM instance for the given model name, using a cached or new factory-created\n * instance.\n *\n * @param modelName Model name to look up.\n * @return Matching {@link BaseLlm} instance.\n * @throws IllegalArgumentException If no factory matches the model name.\n */\n public static BaseLlm getLlm(String modelName) {\n return instances.computeIfAbsent(modelName, LlmRegistry::createLlm);\n }\n\n /**\n * Creates a {@link BaseLlm} by matching the model name against registered factories.\n *\n * @param modelName Model name to match.\n * @return A new {@link BaseLlm} instance.\n * @throws IllegalArgumentException If no factory matches the model name.\n */\n private static BaseLlm createLlm(String modelName) {\n for (Map.Entry entry : llmFactories.entrySet()) {\n if (modelName.matches(entry.getKey())) {\n return entry.getValue().create(modelName);\n }\n }\n throw new IllegalArgumentException(\"Unsupported model: \" + modelName);\n }\n\n /**\n * Registers an LLM factory for testing purposes. Clears cached instances matching the given\n * pattern to ensure test isolation.\n *\n * @param modelNamePattern Regex pattern for matching model names.\n * @param factory The {@link LlmFactory} to register.\n */\n static void registerTestLlm(String modelNamePattern, LlmFactory factory) {\n llmFactories.put(modelNamePattern, factory);\n // Clear any cached instances that match this pattern to ensure test isolation.\n instances.keySet().removeIf(modelName -> modelName.matches(modelNamePattern));\n }\n\n private LlmRegistry() {}\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/applicationintegrationtoolset/IntegrationClient.java", "package com.google.adk.tools.applicationintegrationtoolset;\n\nimport static com.google.common.base.Strings.isNullOrEmpty;\n\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.fasterxml.jackson.databind.node.ObjectNode;\nimport com.google.adk.tools.applicationintegrationtoolset.IntegrationConnectorTool.HttpExecutor;\nimport com.google.common.base.Preconditions;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport java.io.IOException;\nimport java.net.URI;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.util.Arrays;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.Map;\nimport java.util.Objects;\n\n/**\n * Utility class for interacting with Google Cloud Application Integration.\n *\n *

This class provides methods for retrieving OpenAPI spec for an integration or a connection.\n */\npublic class IntegrationClient {\n String project;\n String location;\n String integration;\n List triggers;\n String connection;\n Map> entityOperations;\n List actions;\n private final HttpExecutor httpExecutor;\n public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();\n\n IntegrationClient(\n String project,\n String location,\n String integration,\n List triggers,\n String connection,\n Map> entityOperations,\n List actions,\n HttpExecutor httpExecutor) {\n this.project = project;\n this.location = location;\n this.integration = integration;\n this.triggers = triggers;\n this.connection = connection;\n this.entityOperations = entityOperations;\n this.actions = actions;\n this.httpExecutor = httpExecutor;\n if (!isNullOrEmpty(connection)) {\n validate();\n }\n }\n\n private void validate() {\n // Check if both are null, throw exception\n\n if (this.entityOperations == null && this.actions == null) {\n throw new IllegalArgumentException(\n \"No entity operations or actions provided. Please provide at least one of them.\");\n }\n\n if (this.entityOperations != null) {\n Preconditions.checkArgument(\n !this.entityOperations.isEmpty(), \"entityOperations map cannot be empty\");\n for (Map.Entry> entry : this.entityOperations.entrySet()) {\n String key = entry.getKey();\n List value = entry.getValue();\n Preconditions.checkArgument(\n key != null && !key.isEmpty(),\n \"Enitity in entityOperations map cannot be null or empty\");\n Preconditions.checkArgument(\n value != null, \"Operations for entity '%s' cannot be null\", key);\n for (String str : value) {\n Preconditions.checkArgument(\n str != null && !str.isEmpty(),\n \"Operation for entity '%s' cannot be null or empty\",\n key);\n }\n }\n }\n\n // Validate actions if it's not null\n if (this.actions != null) {\n Preconditions.checkArgument(!this.actions.isEmpty(), \"Actions list cannot be empty\");\n Preconditions.checkArgument(\n this.actions.stream().allMatch(Objects::nonNull),\n \"Actions list cannot contain null values\");\n Preconditions.checkArgument(\n this.actions.stream().noneMatch(String::isEmpty),\n \"Actions list cannot contain empty strings\");\n }\n }\n\n String generateOpenApiSpec() throws Exception {\n String url =\n String.format(\n \"https://%s-integrations.googleapis.com/v1/projects/%s/locations/%s:generateOpenApiSpec\",\n this.location, this.project, this.location);\n\n String jsonRequestBody =\n OBJECT_MAPPER.writeValueAsString(\n ImmutableMap.of(\n \"apiTriggerResources\",\n ImmutableList.of(\n ImmutableMap.of(\n \"integrationResource\",\n this.integration,\n \"triggerId\",\n Arrays.asList(this.triggers))),\n \"fileFormat\",\n \"JSON\"));\n HttpRequest request =\n HttpRequest.newBuilder()\n .uri(URI.create(url))\n .header(\"Authorization\", \"Bearer \" + httpExecutor.getToken())\n .header(\"Content-Type\", \"application/json\")\n .POST(HttpRequest.BodyPublishers.ofString(jsonRequestBody))\n .build();\n HttpResponse response =\n httpExecutor.send(request, HttpResponse.BodyHandlers.ofString());\n\n if (response.statusCode() < 200 || response.statusCode() >= 300) {\n throw new Exception(\"Error fetching OpenAPI spec. Status: \" + response.statusCode());\n }\n return response.body();\n }\n\n @SuppressWarnings(\"unchecked\")\n ObjectNode getOpenApiSpecForConnection(String toolName, String toolInstructions)\n throws IOException, InterruptedException {\n final String integrationName = \"ExecuteConnection\";\n\n ConnectionsClient connectionsClient = createConnectionsClient();\n\n ImmutableMap baseSpecMap = ConnectionsClient.getConnectorBaseSpec();\n ObjectNode connectorSpec = OBJECT_MAPPER.valueToTree(baseSpecMap);\n\n ObjectNode paths = (ObjectNode) connectorSpec.path(\"paths\");\n ObjectNode schemas = (ObjectNode) connectorSpec.path(\"components\").path(\"schemas\");\n\n if (this.entityOperations != null) {\n for (Map.Entry> entry : this.entityOperations.entrySet()) {\n String entity = entry.getKey();\n List operations = entry.getValue();\n\n ConnectionsClient.EntitySchemaAndOperations schemaInfo;\n try {\n schemaInfo = connectionsClient.getEntitySchemaAndOperations(entity);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n throw new IOException(\"Operation was interrupted while getting entity schema\", e);\n }\n\n Map schemaMap = schemaInfo.schema;\n List supportedOperations = schemaInfo.operations;\n\n if (operations == null || operations.isEmpty()) {\n operations = supportedOperations;\n }\n\n String jsonSchemaAsString = OBJECT_MAPPER.writeValueAsString(schemaMap);\n String entityLower = entity.toLowerCase(Locale.ROOT);\n\n schemas.set(\n \"connectorInputPayload_\" + entityLower,\n OBJECT_MAPPER.valueToTree(connectionsClient.connectorPayload(schemaMap)));\n\n for (String operation : operations) {\n String operationLower = operation.toLowerCase(Locale.ROOT);\n String path =\n String.format(\n \"/v2/projects/%s/locations/%s/integrations/%s:execute?triggerId=api_trigger/%s#%s_%s\",\n this.project,\n this.location,\n integrationName,\n integrationName,\n operationLower,\n entityLower);\n\n switch (operationLower) {\n case \"create\":\n paths.set(\n path,\n OBJECT_MAPPER.valueToTree(\n ConnectionsClient.createOperation(entityLower, toolName, toolInstructions)));\n schemas.set(\n \"create_\" + entityLower + \"_Request\",\n OBJECT_MAPPER.valueToTree(ConnectionsClient.createOperationRequest(entityLower)));\n break;\n case \"update\":\n paths.set(\n path,\n OBJECT_MAPPER.valueToTree(\n ConnectionsClient.updateOperation(entityLower, toolName, toolInstructions)));\n schemas.set(\n \"update_\" + entityLower + \"_Request\",\n OBJECT_MAPPER.valueToTree(ConnectionsClient.updateOperationRequest(entityLower)));\n break;\n case \"delete\":\n paths.set(\n path,\n OBJECT_MAPPER.valueToTree(\n ConnectionsClient.deleteOperation(entityLower, toolName, toolInstructions)));\n schemas.set(\n \"delete_\" + entityLower + \"_Request\",\n OBJECT_MAPPER.valueToTree(ConnectionsClient.deleteOperationRequest()));\n break;\n case \"list\":\n paths.set(\n path,\n OBJECT_MAPPER.valueToTree(\n ConnectionsClient.listOperation(\n entityLower, jsonSchemaAsString, toolName, toolInstructions)));\n schemas.set(\n \"list_\" + entityLower + \"_Request\",\n OBJECT_MAPPER.valueToTree(ConnectionsClient.listOperationRequest()));\n break;\n case \"get\":\n paths.set(\n path,\n OBJECT_MAPPER.valueToTree(\n ConnectionsClient.getOperation(\n entityLower, jsonSchemaAsString, toolName, toolInstructions)));\n schemas.set(\n \"get_\" + entityLower + \"_Request\",\n OBJECT_MAPPER.valueToTree(ConnectionsClient.getOperationRequest()));\n break;\n default:\n throw new IllegalArgumentException(\n \"Invalid operation: \" + operation + \" for entity: \" + entity);\n }\n }\n }\n } else if (this.actions != null) {\n for (String action : this.actions) {\n ObjectNode actionDetails =\n OBJECT_MAPPER.valueToTree(connectionsClient.getActionSchema(action));\n\n JsonNode inputSchemaNode = actionDetails.path(\"inputSchema\");\n JsonNode outputSchemaNode = actionDetails.path(\"outputSchema\");\n\n String actionDisplayName = actionDetails.path(\"displayName\").asText(\"\").replace(\" \", \"\");\n String operation = \"EXECUTE_ACTION\";\n\n Map inputSchemaMap = OBJECT_MAPPER.treeToValue(inputSchemaNode, Map.class);\n Map outputSchemaMap =\n OBJECT_MAPPER.treeToValue(outputSchemaNode, Map.class);\n\n if (Objects.equals(action, \"ExecuteCustomQuery\")) {\n schemas.set(\n actionDisplayName + \"_Request\",\n OBJECT_MAPPER.valueToTree(ConnectionsClient.executeCustomQueryRequest()));\n operation = \"EXECUTE_QUERY\";\n } else {\n schemas.set(\n actionDisplayName + \"_Request\",\n OBJECT_MAPPER.valueToTree(ConnectionsClient.actionRequest(actionDisplayName)));\n schemas.set(\n \"connectorInputPayload_\" + actionDisplayName,\n OBJECT_MAPPER.valueToTree(connectionsClient.connectorPayload(inputSchemaMap)));\n }\n\n schemas.set(\n \"connectorOutputPayload_\" + actionDisplayName,\n OBJECT_MAPPER.valueToTree(connectionsClient.connectorPayload(outputSchemaMap)));\n schemas.set(\n actionDisplayName + \"_Response\",\n OBJECT_MAPPER.valueToTree(ConnectionsClient.actionResponse(actionDisplayName)));\n\n String path =\n String.format(\n \"/v2/projects/%s/locations/%s/integrations/%s:execute?triggerId=api_trigger/%s#%s\",\n this.project, this.location, integrationName, integrationName, action);\n\n paths.set(\n path,\n OBJECT_MAPPER.valueToTree(\n ConnectionsClient.getActionOperation(\n action, operation, actionDisplayName, toolName, toolInstructions)));\n }\n } else {\n throw new IllegalArgumentException(\n \"No entity operations or actions provided. Please provide at least one of them.\");\n }\n return connectorSpec;\n }\n\n String getOperationIdFromPathUrl(String openApiSchemaString, String pathUrl) throws Exception {\n JsonNode topLevelNode = OBJECT_MAPPER.readTree(openApiSchemaString);\n JsonNode specNode = topLevelNode.path(\"openApiSpec\");\n if (specNode.isMissingNode() || !specNode.isTextual()) {\n throw new IllegalArgumentException(\n \"Failed to get OpenApiSpec, please check the project and region for the integration.\");\n }\n JsonNode rootNode = OBJECT_MAPPER.readTree(specNode.asText());\n JsonNode paths = rootNode.path(\"paths\");\n\n Iterator> pathsFields = paths.fields();\n while (pathsFields.hasNext()) {\n Map.Entry pathEntry = pathsFields.next();\n String currentPath = pathEntry.getKey();\n if (!currentPath.equals(pathUrl)) {\n continue;\n }\n JsonNode pathItem = pathEntry.getValue();\n\n Iterator> methods = pathItem.fields();\n while (methods.hasNext()) {\n Map.Entry methodEntry = methods.next();\n JsonNode operationNode = methodEntry.getValue();\n\n if (operationNode.has(\"operationId\")) {\n return operationNode.path(\"operationId\").asText();\n }\n }\n }\n throw new Exception(\"Could not find operationId for pathUrl: \" + pathUrl);\n }\n\n ConnectionsClient createConnectionsClient() {\n return new ConnectionsClient(\n this.project, this.location, this.connection, this.httpExecutor, OBJECT_MAPPER);\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/sessions/SessionUtils.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.genai.types.Blob;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.Part;\nimport java.util.ArrayList;\nimport java.util.Base64;\nimport java.util.List;\nimport java.util.Optional;\n\n/** Utility functions for session service. */\npublic final class SessionUtils {\n\n public SessionUtils() {}\n\n /** Base64-encodes inline blobs in content. */\n public static Content encodeContent(Content content) {\n List encodedParts = new ArrayList<>();\n for (Part part : content.parts().orElse(ImmutableList.of())) {\n boolean isInlineDataPresent = false;\n if (part.inlineData() != null) {\n Optional inlineDataOptional = part.inlineData();\n if (inlineDataOptional.isPresent()) {\n Blob inlineDataBlob = inlineDataOptional.get();\n Optional dataOptional = inlineDataBlob.data();\n if (dataOptional.isPresent()) {\n byte[] dataBytes = dataOptional.get();\n byte[] encodedData = Base64.getEncoder().encode(dataBytes);\n encodedParts.add(\n part.toBuilder().inlineData(Blob.builder().data(encodedData).build()).build());\n isInlineDataPresent = true;\n }\n }\n }\n if (!isInlineDataPresent) {\n encodedParts.add(part);\n }\n }\n return toContent(encodedParts, content.role());\n }\n\n /** Decodes Base64-encoded inline blobs in content. */\n public static Content decodeContent(Content content) {\n List decodedParts = new ArrayList<>();\n for (Part part : content.parts().orElse(ImmutableList.of())) {\n boolean isInlineDataPresent = false;\n if (part.inlineData() != null) {\n Optional inlineDataOptional = part.inlineData();\n if (inlineDataOptional.isPresent()) {\n Blob inlineDataBlob = inlineDataOptional.get();\n Optional dataOptional = inlineDataBlob.data();\n if (dataOptional.isPresent()) {\n byte[] dataBytes = dataOptional.get();\n byte[] decodedData = Base64.getDecoder().decode(dataBytes);\n decodedParts.add(\n part.toBuilder().inlineData(Blob.builder().data(decodedData).build()).build());\n isInlineDataPresent = true;\n }\n }\n }\n if (!isInlineDataPresent) {\n decodedParts.add(part);\n }\n }\n return toContent(decodedParts, content.role());\n }\n\n /** Builds content from parts and optional role. */\n private static Content toContent(List parts, Optional role) {\n Content.Builder contentBuilder = Content.builder().parts(parts);\n role.ifPresent(contentBuilder::role);\n return contentBuilder.build();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/applicationintegrationtoolset/ConnectionsClient.java", "package com.google.adk.tools.applicationintegrationtoolset;\n\nimport static com.google.common.base.Strings.isNullOrEmpty;\n\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.google.adk.tools.applicationintegrationtoolset.IntegrationConnectorTool.HttpExecutor;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport java.io.IOException;\nimport java.net.URI;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\n\n/**\n * Utility class for interacting with the Google Cloud Connectors API.\n *\n *

This class provides methods to fetch connection details, schemas for entities and actions, and\n * to generate OpenAPI specifications for creating tools based on these connections.\n */\npublic class ConnectionsClient {\n\n private final String project;\n private final String location;\n private final String connection;\n private static final String CONNECTOR_URL = \"https://connectors.googleapis.com\";\n private final HttpExecutor httpExecutor;\n private final ObjectMapper objectMapper;\n\n /** Represents details of a connection. */\n public static class ConnectionDetails {\n public String name;\n public String serviceName;\n public String host;\n }\n\n /** Represents the schema and available operations for an entity. */\n public static class EntitySchemaAndOperations {\n public Map schema;\n public List operations;\n }\n\n /** Represents the schema for an action. */\n public static class ActionSchema {\n public Map inputSchema;\n public Map outputSchema;\n public String description;\n public String displayName;\n }\n\n /**\n * Initializes the ConnectionsClient.\n *\n * @param project The Google Cloud project ID.\n * @param location The Google Cloud location (e.g., us-central1).\n * @param connection The connection name.\n */\n public ConnectionsClient(\n String project,\n String location,\n String connection,\n HttpExecutor httpExecutor,\n ObjectMapper objectMapper) {\n this.project = project;\n this.location = location;\n this.connection = connection;\n this.httpExecutor = httpExecutor;\n this.objectMapper = objectMapper;\n }\n\n /**\n * Retrieves service details for a given connection.\n *\n * @return A {@link ConnectionDetails} object with the connection's info.\n * @throws IOException If there is an issue with network communication or credentials.\n * @throws InterruptedException If the thread is interrupted during the API call.\n */\n public ConnectionDetails getConnectionDetails() throws IOException, InterruptedException {\n String url =\n String.format(\n \"%s/v1/projects/%s/locations/%s/connections/%s?view=BASIC\",\n CONNECTOR_URL, project, location, connection);\n\n HttpResponse response = executeApiCall(url);\n Map connectionData = parseJson(response.body());\n\n ConnectionDetails details = new ConnectionDetails();\n details.name = (String) connectionData.getOrDefault(\"name\", \"\");\n details.serviceName = (String) connectionData.getOrDefault(\"serviceDirectory\", \"\");\n details.host = (String) connectionData.getOrDefault(\"host\", \"\");\n if (details.host != null && !details.host.isEmpty()) {\n details.serviceName = (String) connectionData.getOrDefault(\"tlsServiceDirectory\", \"\");\n }\n return details;\n }\n\n /**\n * Retrieves the JSON schema and available operations for a given entity.\n *\n * @param entity The entity name.\n * @return A {@link EntitySchemaAndOperations} object.\n * @throws IOException If there is an issue with network communication or credentials.\n * @throws InterruptedException If the thread is interrupted during polling.\n */\n @SuppressWarnings(\"unchecked\")\n public EntitySchemaAndOperations getEntitySchemaAndOperations(String entity)\n throws IOException, InterruptedException {\n String url =\n String.format(\n \"%s/v1/projects/%s/locations/%s/connections/%s/connectionSchemaMetadata:getEntityType?entityId=%s\",\n CONNECTOR_URL, project, location, connection, entity);\n\n HttpResponse initialResponse = executeApiCall(url);\n String operationId = (String) parseJson(initialResponse.body()).get(\"name\");\n\n if (isNullOrEmpty(operationId)) {\n throw new IOException(\"Failed to get operation ID for entity: \" + entity);\n }\n\n Map operationResponse = pollOperation(operationId);\n Map responseData =\n (Map) operationResponse.getOrDefault(\"response\", ImmutableMap.of());\n\n Map schema =\n (Map) responseData.getOrDefault(\"jsonSchema\", ImmutableMap.of());\n List operations =\n (List) responseData.getOrDefault(\"operations\", ImmutableList.of());\n EntitySchemaAndOperations entitySchemaAndOperations = new EntitySchemaAndOperations();\n entitySchemaAndOperations.schema = schema;\n entitySchemaAndOperations.operations = operations;\n return entitySchemaAndOperations;\n }\n\n /**\n * Retrieves the input and output JSON schema for a given action.\n *\n * @param action The action name.\n * @return An {@link ActionSchema} object.\n * @throws IOException If there is an issue with network communication or credentials.\n * @throws InterruptedException If the thread is interrupted during polling.\n */\n @SuppressWarnings(\"unchecked\")\n public ActionSchema getActionSchema(String action) throws IOException, InterruptedException {\n String url =\n String.format(\n \"%s/v1/projects/%s/locations/%s/connections/%s/connectionSchemaMetadata:getAction?actionId=%s\",\n CONNECTOR_URL, project, location, connection, action);\n\n HttpResponse initialResponse = executeApiCall(url);\n String operationId = (String) parseJson(initialResponse.body()).get(\"name\");\n\n if (isNullOrEmpty(operationId)) {\n throw new IOException(\"Failed to get operation ID for action: \" + action);\n }\n\n Map operationResponse = pollOperation(operationId);\n Map responseData =\n (Map) operationResponse.getOrDefault(\"response\", ImmutableMap.of());\n\n ActionSchema actionSchema = new ActionSchema();\n actionSchema.inputSchema =\n (Map) responseData.getOrDefault(\"inputJsonSchema\", ImmutableMap.of());\n actionSchema.outputSchema =\n (Map) responseData.getOrDefault(\"outputJsonSchema\", ImmutableMap.of());\n actionSchema.description = (String) responseData.getOrDefault(\"description\", \"\");\n actionSchema.displayName = (String) responseData.getOrDefault(\"displayName\", \"\");\n\n return actionSchema;\n }\n\n private HttpResponse executeApiCall(String url) throws IOException, InterruptedException {\n HttpRequest request =\n HttpRequest.newBuilder()\n .uri(URI.create(url))\n .header(\"Content-Type\", \"application/json\")\n .header(\"Authorization\", \"Bearer \" + httpExecutor.getToken())\n .GET()\n .build();\n\n HttpResponse response =\n httpExecutor.send(request, HttpResponse.BodyHandlers.ofString());\n\n if (response.statusCode() >= 400) {\n String body = response.body();\n if (response.statusCode() == 400 || response.statusCode() == 404) {\n throw new IllegalArgumentException(\n String.format(\n \"Invalid request. Please check the provided values of project(%s), location(%s),\"\n + \" connection(%s). Error: %s\",\n project, location, connection, body));\n }\n if (response.statusCode() == 401 || response.statusCode() == 403) {\n throw new SecurityException(\n String.format(\"Permission error (status %d): %s\", response.statusCode(), body));\n }\n throw new IOException(\n String.format(\"API call failed with status %d: %s\", response.statusCode(), body));\n }\n return response;\n }\n\n private Map pollOperation(String operationId)\n throws IOException, InterruptedException {\n boolean operationDone = false;\n Map operationResponse = null;\n\n while (!operationDone) {\n String getOperationUrl = String.format(\"%s/v1/%s\", CONNECTOR_URL, operationId);\n HttpResponse response = executeApiCall(getOperationUrl);\n operationResponse = parseJson(response.body());\n\n Object doneObj = operationResponse.get(\"done\");\n if (doneObj instanceof Boolean b) {\n operationDone = b;\n }\n\n if (!operationDone) {\n Thread.sleep(1000);\n }\n }\n return operationResponse;\n }\n\n /**\n * Converts a JSON Schema dictionary to an OpenAPI schema dictionary.\n *\n * @param jsonSchema The input JSON schema map.\n * @return The converted OpenAPI schema map.\n */\n public Map convertJsonSchemaToOpenApiSchema(Map jsonSchema) {\n Map openapiSchema = new HashMap<>();\n\n if (jsonSchema.containsKey(\"description\")) {\n openapiSchema.put(\"description\", jsonSchema.get(\"description\"));\n }\n\n if (jsonSchema.containsKey(\"type\")) {\n Object type = jsonSchema.get(\"type\");\n if (type instanceof List) {\n List typeList = (List) type;\n if (typeList.contains(\"null\")) {\n openapiSchema.put(\"nullable\", true);\n typeList.stream()\n .filter(t -> t instanceof String && !t.equals(\"null\"))\n .findFirst()\n .ifPresent(t -> openapiSchema.put(\"type\", t));\n } else if (!typeList.isEmpty()) {\n openapiSchema.put(\"type\", typeList.get(0));\n }\n } else {\n openapiSchema.put(\"type\", type);\n }\n }\n if (Objects.equals(openapiSchema.get(\"type\"), \"object\")\n && jsonSchema.containsKey(\"properties\")) {\n @SuppressWarnings(\"unchecked\")\n Map> properties =\n (Map>) jsonSchema.get(\"properties\");\n Map convertedProperties = new HashMap<>();\n for (Map.Entry> entry : properties.entrySet()) {\n convertedProperties.put(entry.getKey(), convertJsonSchemaToOpenApiSchema(entry.getValue()));\n }\n openapiSchema.put(\"properties\", convertedProperties);\n } else if (Objects.equals(openapiSchema.get(\"type\"), \"array\")\n && jsonSchema.containsKey(\"items\")) {\n @SuppressWarnings(\"unchecked\")\n Map itemsSchema = (Map) jsonSchema.get(\"items\");\n openapiSchema.put(\"items\", convertJsonSchemaToOpenApiSchema(itemsSchema));\n }\n\n return openapiSchema;\n }\n\n public Map connectorPayload(Map jsonSchema) {\n return convertJsonSchemaToOpenApiSchema(jsonSchema);\n }\n\n private Map parseJson(String json) throws IOException {\n return objectMapper.readValue(json, new TypeReference<>() {});\n }\n\n public static ImmutableMap getConnectorBaseSpec() {\n return ImmutableMap.ofEntries(\n Map.entry(\"openapi\", \"3.0.1\"),\n Map.entry(\n \"info\",\n ImmutableMap.of(\n \"title\", \"ExecuteConnection\",\n \"description\", \"This tool can execute a query on connection\",\n \"version\", \"4\")),\n Map.entry(\n \"servers\",\n ImmutableList.of(ImmutableMap.of(\"url\", \"https://integrations.googleapis.com\"))),\n Map.entry(\n \"security\",\n ImmutableList.of(\n ImmutableMap.of(\n \"google_auth\",\n ImmutableList.of(\"https://www.googleapis.com/auth/cloud-platform\")))),\n Map.entry(\"paths\", ImmutableMap.of()),\n Map.entry(\n \"components\",\n ImmutableMap.ofEntries(\n Map.entry(\n \"schemas\",\n ImmutableMap.ofEntries(\n Map.entry(\n \"operation\",\n ImmutableMap.of(\n \"type\", \"string\",\n \"default\", \"LIST_ENTITIES\",\n \"description\",\n \"Operation to execute. Possible values are LIST_ENTITIES,\"\n + \" GET_ENTITY, CREATE_ENTITY, UPDATE_ENTITY, DELETE_ENTITY\"\n + \" in case of entities. EXECUTE_ACTION in case of\"\n + \" actions. and EXECUTE_QUERY in case of custom\"\n + \" queries.\")),\n Map.entry(\n \"entityId\",\n ImmutableMap.of(\"type\", \"string\", \"description\", \"Name of the entity\")),\n Map.entry(\"connectorInputPayload\", ImmutableMap.of(\"type\", \"object\")),\n Map.entry(\n \"filterClause\",\n ImmutableMap.of(\n \"type\", \"string\",\n \"default\", \"\",\n \"description\", \"WHERE clause in SQL query\")),\n Map.entry(\n \"pageSize\",\n ImmutableMap.of(\n \"type\", \"integer\",\n \"default\", 50,\n \"description\", \"Number of entities to return in the response\")),\n Map.entry(\n \"pageToken\",\n ImmutableMap.of(\n \"type\", \"string\",\n \"default\", \"\",\n \"description\", \"Page token to return the next page of entities\")),\n Map.entry(\n \"connectionName\",\n ImmutableMap.of(\n \"type\", \"string\",\n \"default\", \"\",\n \"description\", \"Connection resource name to run the query for\")),\n Map.entry(\n \"serviceName\",\n ImmutableMap.of(\n \"type\", \"string\",\n \"default\", \"\",\n \"description\", \"Service directory for the connection\")),\n Map.entry(\n \"host\",\n ImmutableMap.of(\n \"type\", \"string\",\n \"default\", \"\",\n \"description\", \"Host name incase of tls service directory\")),\n Map.entry(\n \"entity\",\n ImmutableMap.of(\n \"type\", \"string\",\n \"default\", \"Issues\",\n \"description\", \"Entity to run the query for\")),\n Map.entry(\n \"action\",\n ImmutableMap.of(\n \"type\", \"string\",\n \"default\", \"ExecuteCustomQuery\",\n \"description\", \"Action to run the query for\")),\n Map.entry(\n \"query\",\n ImmutableMap.of(\n \"type\", \"string\",\n \"default\", \"\",\n \"description\", \"Custom Query to execute on the connection\")),\n Map.entry(\n \"timeout\",\n ImmutableMap.of(\n \"type\", \"integer\",\n \"default\", 120,\n \"description\", \"Timeout in seconds for execution of custom query\")),\n Map.entry(\n \"sortByColumns\",\n ImmutableMap.of(\n \"type\",\n \"array\",\n \"items\",\n ImmutableMap.of(\"type\", \"string\"),\n \"default\",\n ImmutableList.of(),\n \"description\",\n \"Column to sort the results by\")),\n Map.entry(\"connectorOutputPayload\", ImmutableMap.of(\"type\", \"object\")),\n Map.entry(\"nextPageToken\", ImmutableMap.of(\"type\", \"string\")),\n Map.entry(\n \"execute-connector_Response\",\n ImmutableMap.of(\n \"required\", ImmutableList.of(\"connectorOutputPayload\"),\n \"type\", \"object\",\n \"properties\",\n ImmutableMap.of(\n \"connectorOutputPayload\",\n ImmutableMap.of(\n \"$ref\", \"#/components/schemas/connectorOutputPayload\"),\n \"nextPageToken\",\n ImmutableMap.of(\n \"$ref\", \"#/components/schemas/nextPageToken\")))))),\n Map.entry(\n \"securitySchemes\",\n ImmutableMap.of(\n \"google_auth\",\n ImmutableMap.of(\n \"type\",\n \"oauth2\",\n \"flows\",\n ImmutableMap.of(\n \"implicit\",\n ImmutableMap.of(\n \"authorizationUrl\",\n \"https://accounts.google.com/o/oauth2/auth\",\n \"scopes\",\n ImmutableMap.of(\n \"https://www.googleapis.com/auth/cloud-platform\",\n \"Auth for google cloud services\")))))))));\n }\n\n public static ImmutableMap getActionOperation(\n String action,\n String operation,\n String actionDisplayName,\n String toolName,\n String toolInstructions) {\n String description = \"Use this tool to execute \" + action;\n if (Objects.equals(operation, \"EXECUTE_QUERY\")) {\n description +=\n \" Use pageSize = 50 and timeout = 120 until user specifies a different value\"\n + \" otherwise. If user provides a query in natural language, convert it to SQL query\"\n + \" and then execute it using the tool.\";\n }\n\n return ImmutableMap.of(\n \"post\",\n ImmutableMap.ofEntries(\n Map.entry(\"summary\", actionDisplayName),\n Map.entry(\"description\", description + \" \" + toolInstructions),\n Map.entry(\"operationId\", toolName + \"_\" + actionDisplayName),\n Map.entry(\"x-action\", action),\n Map.entry(\"x-operation\", operation),\n Map.entry(\n \"requestBody\",\n ImmutableMap.of(\n \"content\",\n ImmutableMap.of(\n \"application/json\",\n ImmutableMap.of(\n \"schema\",\n ImmutableMap.of(\n \"$ref\",\n String.format(\n \"#/components/schemas/%s_Request\", actionDisplayName)))))),\n Map.entry(\n \"responses\",\n ImmutableMap.of(\n \"200\",\n ImmutableMap.of(\n \"description\",\n \"Success response\",\n \"content\",\n ImmutableMap.of(\n \"application/json\",\n ImmutableMap.of(\n \"schema\",\n ImmutableMap.of(\n \"$ref\",\n String.format(\n \"#/components/schemas/%s_Response\",\n actionDisplayName)))))))));\n }\n\n public static ImmutableMap listOperation(\n String entity, String schemaAsString, String toolName, String toolInstructions) {\n return ImmutableMap.of(\n \"post\",\n ImmutableMap.ofEntries(\n Map.entry(\"summary\", \"List \" + entity),\n Map.entry(\n \"description\",\n String.format(\n \"Returns the list of %s data. If the page token was available in the response,\"\n + \" let users know there are more records available. Ask if the user wants\"\n + \" to fetch the next page of results. When passing filter use the\"\n + \" following format: `field_name1='value1' AND field_name2='value2'`. %s\",\n entity, toolInstructions)),\n Map.entry(\"x-operation\", \"LIST_ENTITIES\"),\n Map.entry(\"x-entity\", entity),\n Map.entry(\"operationId\", toolName + \"_list_\" + entity),\n Map.entry(\n \"requestBody\",\n ImmutableMap.of(\n \"content\",\n ImmutableMap.of(\n \"application/json\",\n ImmutableMap.of(\n \"schema\",\n ImmutableMap.of(\n \"$ref\", \"#/components/schemas/list_\" + entity + \"_Request\"))))),\n Map.entry(\n \"responses\",\n ImmutableMap.of(\n \"200\",\n ImmutableMap.of(\n \"description\",\n \"Success response\",\n \"content\",\n ImmutableMap.of(\n \"application/json\",\n ImmutableMap.of(\n \"schema\",\n ImmutableMap.of(\n \"description\",\n String.format(\n \"Returns a list of %s of json schema: %s\",\n entity, schemaAsString),\n \"$ref\",\n \"#/components/schemas/execute-connector_Response\"))))))));\n }\n\n public static ImmutableMap getOperation(\n String entity, String schemaAsString, String toolName, String toolInstructions) {\n return ImmutableMap.of(\n \"post\",\n ImmutableMap.ofEntries(\n Map.entry(\"summary\", \"Get \" + entity),\n Map.entry(\n \"description\",\n String.format(\"Returns the details of the %s. %s\", entity, toolInstructions)),\n Map.entry(\"operationId\", toolName + \"_get_\" + entity),\n Map.entry(\"x-operation\", \"GET_ENTITY\"),\n Map.entry(\"x-entity\", entity),\n Map.entry(\n \"requestBody\",\n ImmutableMap.of(\n \"content\",\n ImmutableMap.of(\n \"application/json\",\n ImmutableMap.of(\n \"schema\",\n ImmutableMap.of(\n \"$ref\", \"#/components/schemas/get_\" + entity + \"_Request\"))))),\n Map.entry(\n \"responses\",\n ImmutableMap.of(\n \"200\",\n ImmutableMap.of(\n \"description\",\n \"Success response\",\n \"content\",\n ImmutableMap.of(\n \"application/json\",\n ImmutableMap.of(\n \"schema\",\n ImmutableMap.of(\n \"description\",\n String.format(\n \"Returns %s of json schema: %s\", entity, schemaAsString),\n \"$ref\",\n \"#/components/schemas/execute-connector_Response\"))))))));\n }\n\n public static ImmutableMap createOperation(\n String entity, String toolName, String toolInstructions) {\n return ImmutableMap.of(\n \"post\",\n ImmutableMap.ofEntries(\n Map.entry(\"summary\", \"Creates a new \" + entity),\n Map.entry(\n \"description\", String.format(\"Creates a new %s. %s\", entity, toolInstructions)),\n Map.entry(\"x-operation\", \"CREATE_ENTITY\"),\n Map.entry(\"x-entity\", entity),\n Map.entry(\"operationId\", toolName + \"_create_\" + entity),\n Map.entry(\n \"requestBody\",\n ImmutableMap.of(\n \"content\",\n ImmutableMap.of(\n \"application/json\",\n ImmutableMap.of(\n \"schema\",\n ImmutableMap.of(\n \"$ref\", \"#/components/schemas/create_\" + entity + \"_Request\"))))),\n Map.entry(\n \"responses\",\n ImmutableMap.of(\n \"200\",\n ImmutableMap.of(\n \"description\",\n \"Success response\",\n \"content\",\n ImmutableMap.of(\n \"application/json\",\n ImmutableMap.of(\n \"schema\",\n ImmutableMap.of(\n \"$ref\",\n \"#/components/schemas/execute-connector_Response\"))))))));\n }\n\n public static ImmutableMap updateOperation(\n String entity, String toolName, String toolInstructions) {\n return ImmutableMap.of(\n \"post\",\n ImmutableMap.ofEntries(\n Map.entry(\"summary\", \"Updates the \" + entity),\n Map.entry(\"description\", String.format(\"Updates the %s. %s\", entity, toolInstructions)),\n Map.entry(\"x-operation\", \"UPDATE_ENTITY\"),\n Map.entry(\"x-entity\", entity),\n Map.entry(\"operationId\", toolName + \"_update_\" + entity),\n Map.entry(\n \"requestBody\",\n ImmutableMap.of(\n \"content\",\n ImmutableMap.of(\n \"application/json\",\n ImmutableMap.of(\n \"schema\",\n ImmutableMap.of(\n \"$ref\", \"#/components/schemas/update_\" + entity + \"_Request\"))))),\n Map.entry(\n \"responses\",\n ImmutableMap.of(\n \"200\",\n ImmutableMap.of(\n \"description\",\n \"Success response\",\n \"content\",\n ImmutableMap.of(\n \"application/json\",\n ImmutableMap.of(\n \"schema\",\n ImmutableMap.of(\n \"$ref\",\n \"#/components/schemas/execute-connector_Response\"))))))));\n }\n\n public static ImmutableMap deleteOperation(\n String entity, String toolName, String toolInstructions) {\n return ImmutableMap.of(\n \"post\",\n ImmutableMap.ofEntries(\n Map.entry(\"summary\", \"Delete the \" + entity),\n Map.entry(\"description\", String.format(\"Deletes the %s. %s\", entity, toolInstructions)),\n Map.entry(\"x-operation\", \"DELETE_ENTITY\"),\n Map.entry(\"x-entity\", entity),\n Map.entry(\"operationId\", toolName + \"_delete_\" + entity),\n Map.entry(\n \"requestBody\",\n ImmutableMap.of(\n \"content\",\n ImmutableMap.of(\n \"application/json\",\n ImmutableMap.of(\n \"schema\",\n ImmutableMap.of(\n \"$ref\", \"#/components/schemas/delete_\" + entity + \"_Request\"))))),\n Map.entry(\n \"responses\",\n ImmutableMap.of(\n \"200\",\n ImmutableMap.of(\n \"description\",\n \"Success response\",\n \"content\",\n ImmutableMap.of(\n \"application/json\",\n ImmutableMap.of(\n \"schema\",\n ImmutableMap.of(\n \"$ref\",\n \"#/components/schemas/execute-connector_Response\"))))))));\n }\n\n public static ImmutableMap createOperationRequest(String entity) {\n return ImmutableMap.of(\n \"type\",\n \"object\",\n \"required\",\n ImmutableList.of(\n \"connectorInputPayload\",\n \"operation\",\n \"connectionName\",\n \"serviceName\",\n \"host\",\n \"entity\"),\n \"properties\",\n ImmutableMap.ofEntries(\n Map.entry(\n \"connectorInputPayload\",\n ImmutableMap.of(\"$ref\", \"#/components/schemas/connectorInputPayload_\" + entity)),\n Map.entry(\"operation\", ImmutableMap.of(\"$ref\", \"#/components/schemas/operation\")),\n Map.entry(\n \"connectionName\", ImmutableMap.of(\"$ref\", \"#/components/schemas/connectionName\")),\n Map.entry(\"serviceName\", ImmutableMap.of(\"$ref\", \"#/components/schemas/serviceName\")),\n Map.entry(\"host\", ImmutableMap.of(\"$ref\", \"#/components/schemas/host\")),\n Map.entry(\"entity\", ImmutableMap.of(\"$ref\", \"#/components/schemas/entity\"))));\n }\n\n public static ImmutableMap updateOperationRequest(String entity) {\n return ImmutableMap.of(\n \"type\",\n \"object\",\n \"required\",\n ImmutableList.of(\n \"connectorInputPayload\",\n \"entityId\",\n \"operation\",\n \"connectionName\",\n \"serviceName\",\n \"host\",\n \"entity\"),\n \"properties\",\n ImmutableMap.ofEntries(\n Map.entry(\n \"connectorInputPayload\",\n ImmutableMap.of(\"$ref\", \"#/components/schemas/connectorInputPayload_\" + entity)),\n Map.entry(\"entityId\", ImmutableMap.of(\"$ref\", \"#/components/schemas/entityId\")),\n Map.entry(\"operation\", ImmutableMap.of(\"$ref\", \"#/components/schemas/operation\")),\n Map.entry(\n \"connectionName\", ImmutableMap.of(\"$ref\", \"#/components/schemas/connectionName\")),\n Map.entry(\"serviceName\", ImmutableMap.of(\"$ref\", \"#/components/schemas/serviceName\")),\n Map.entry(\"host\", ImmutableMap.of(\"$ref\", \"#/components/schemas/host\")),\n Map.entry(\"entity\", ImmutableMap.of(\"$ref\", \"#/components/schemas/entity\")),\n Map.entry(\n \"filterClause\", ImmutableMap.of(\"$ref\", \"#/components/schemas/filterClause\"))));\n }\n\n public static ImmutableMap getOperationRequest() {\n return ImmutableMap.of(\n \"type\",\n \"object\",\n \"required\",\n ImmutableList.of(\n \"entityId\", \"operation\", \"connectionName\", \"serviceName\", \"host\", \"entity\"),\n \"properties\",\n ImmutableMap.ofEntries(\n Map.entry(\"entityId\", ImmutableMap.of(\"$ref\", \"#/components/schemas/entityId\")),\n Map.entry(\"operation\", ImmutableMap.of(\"$ref\", \"#/components/schemas/operation\")),\n Map.entry(\n \"connectionName\", ImmutableMap.of(\"$ref\", \"#/components/schemas/connectionName\")),\n Map.entry(\"serviceName\", ImmutableMap.of(\"$ref\", \"#/components/schemas/serviceName\")),\n Map.entry(\"host\", ImmutableMap.of(\"$ref\", \"#/components/schemas/host\")),\n Map.entry(\"entity\", ImmutableMap.of(\"$ref\", \"#/components/schemas/entity\"))));\n }\n\n public static ImmutableMap deleteOperationRequest() {\n return ImmutableMap.of(\n \"type\",\n \"object\",\n \"required\",\n ImmutableList.of(\n \"entityId\", \"operation\", \"connectionName\", \"serviceName\", \"host\", \"entity\"),\n \"properties\",\n ImmutableMap.ofEntries(\n Map.entry(\"entityId\", ImmutableMap.of(\"$ref\", \"#/components/schemas/entityId\")),\n Map.entry(\"operation\", ImmutableMap.of(\"$ref\", \"#/components/schemas/operation\")),\n Map.entry(\n \"connectionName\", ImmutableMap.of(\"$ref\", \"#/components/schemas/connectionName\")),\n Map.entry(\"serviceName\", ImmutableMap.of(\"$ref\", \"#/components/schemas/serviceName\")),\n Map.entry(\"host\", ImmutableMap.of(\"$ref\", \"#/components/schemas/host\")),\n Map.entry(\"entity\", ImmutableMap.of(\"$ref\", \"#/components/schemas/entity\")),\n Map.entry(\n \"filterClause\", ImmutableMap.of(\"$ref\", \"#/components/schemas/filterClause\"))));\n }\n\n public static ImmutableMap listOperationRequest() {\n return ImmutableMap.of(\n \"type\",\n \"object\",\n \"required\",\n ImmutableList.of(\"operation\", \"connectionName\", \"serviceName\", \"host\", \"entity\"),\n \"properties\",\n ImmutableMap.ofEntries(\n Map.entry(\"filterClause\", ImmutableMap.of(\"$ref\", \"#/components/schemas/filterClause\")),\n Map.entry(\"pageSize\", ImmutableMap.of(\"$ref\", \"#/components/schemas/pageSize\")),\n Map.entry(\"pageToken\", ImmutableMap.of(\"$ref\", \"#/components/schemas/pageToken\")),\n Map.entry(\"operation\", ImmutableMap.of(\"$ref\", \"#/components/schemas/operation\")),\n Map.entry(\n \"connectionName\", ImmutableMap.of(\"$ref\", \"#/components/schemas/connectionName\")),\n Map.entry(\"serviceName\", ImmutableMap.of(\"$ref\", \"#/components/schemas/serviceName\")),\n Map.entry(\"host\", ImmutableMap.of(\"$ref\", \"#/components/schemas/host\")),\n Map.entry(\"entity\", ImmutableMap.of(\"$ref\", \"#/components/schemas/entity\")),\n Map.entry(\n \"sortByColumns\", ImmutableMap.of(\"$ref\", \"#/components/schemas/sortByColumns\"))));\n }\n\n public static ImmutableMap actionRequest(String action) {\n return ImmutableMap.of(\n \"type\",\n \"object\",\n \"required\",\n ImmutableList.of(\n \"operation\",\n \"connectionName\",\n \"serviceName\",\n \"host\",\n \"action\",\n \"connectorInputPayload\"),\n \"properties\",\n ImmutableMap.ofEntries(\n Map.entry(\"operation\", ImmutableMap.of(\"$ref\", \"#/components/schemas/operation\")),\n Map.entry(\n \"connectionName\", ImmutableMap.of(\"$ref\", \"#/components/schemas/connectionName\")),\n Map.entry(\"serviceName\", ImmutableMap.of(\"$ref\", \"#/components/schemas/serviceName\")),\n Map.entry(\"host\", ImmutableMap.of(\"$ref\", \"#/components/schemas/host\")),\n Map.entry(\"action\", ImmutableMap.of(\"$ref\", \"#/components/schemas/action\")),\n Map.entry(\n \"connectorInputPayload\",\n ImmutableMap.of(\"$ref\", \"#/components/schemas/connectorInputPayload_\" + action))));\n }\n\n public static ImmutableMap actionResponse(String action) {\n return ImmutableMap.of(\n \"type\",\n \"object\",\n \"properties\",\n ImmutableMap.of(\n \"connectorOutputPayload\",\n ImmutableMap.of(\"$ref\", \"#/components/schemas/connectorOutputPayload_\" + action)));\n }\n\n public static ImmutableMap executeCustomQueryRequest() {\n return ImmutableMap.of(\n \"type\",\n \"object\",\n \"required\",\n ImmutableList.of(\n \"operation\",\n \"connectionName\",\n \"serviceName\",\n \"host\",\n \"action\",\n \"query\",\n \"timeout\",\n \"pageSize\"),\n \"properties\",\n ImmutableMap.ofEntries(\n Map.entry(\"operation\", ImmutableMap.of(\"$ref\", \"#/components/schemas/operation\")),\n Map.entry(\n \"connectionName\", ImmutableMap.of(\"$ref\", \"#/components/schemas/connectionName\")),\n Map.entry(\"serviceName\", ImmutableMap.of(\"$ref\", \"#/components/schemas/serviceName\")),\n Map.entry(\"host\", ImmutableMap.of(\"$ref\", \"#/components/schemas/host\")),\n Map.entry(\"action\", ImmutableMap.of(\"$ref\", \"#/components/schemas/action\")),\n Map.entry(\"query\", ImmutableMap.of(\"$ref\", \"#/components/schemas/query\")),\n Map.entry(\"timeout\", ImmutableMap.of(\"$ref\", \"#/components/schemas/timeout\")),\n Map.entry(\"pageSize\", ImmutableMap.of(\"$ref\", \"#/components/schemas/pageSize\"))));\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/memory/InMemoryMemoryService.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.memory;\n\nimport static com.google.common.collect.ImmutableList.toImmutableList;\n\nimport com.google.adk.events.Event;\nimport com.google.adk.sessions.Session;\nimport com.google.common.base.Strings;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.genai.types.Part;\nimport io.reactivex.rxjava3.core.Completable;\nimport io.reactivex.rxjava3.core.Single;\nimport java.time.Instant;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\n/**\n * An in-memory memory service for prototyping purposes only.\n *\n *

Uses keyword matching instead of semantic search.\n */\npublic final class InMemoryMemoryService implements BaseMemoryService {\n\n // Pattern to extract words, matching the Python version.\n private static final Pattern WORD_PATTERN = Pattern.compile(\"[A-Za-z]+\");\n\n /** Keys are \"app_name/user_id\", values are maps of \"session_id\" to a list of events. */\n private final Map>> sessionEvents;\n\n public InMemoryMemoryService() {\n this.sessionEvents = new ConcurrentHashMap<>();\n }\n\n private static String userKey(String appName, String userId) {\n return appName + \"/\" + userId;\n }\n\n @Override\n public Completable addSessionToMemory(Session session) {\n return Completable.fromAction(\n () -> {\n String key = userKey(session.appName(), session.userId());\n Map> userSessions =\n sessionEvents.computeIfAbsent(key, k -> new ConcurrentHashMap<>());\n ImmutableList nonEmptyEvents =\n session.events().stream()\n .filter(\n event ->\n event.content().isPresent()\n && event.content().get().parts().isPresent()\n && !event.content().get().parts().get().isEmpty())\n .collect(toImmutableList());\n userSessions.put(session.id(), nonEmptyEvents);\n });\n }\n\n @Override\n public Single searchMemory(String appName, String userId, String query) {\n return Single.fromCallable(\n () -> {\n String key = userKey(appName, userId);\n\n if (!sessionEvents.containsKey(key)) {\n return SearchMemoryResponse.builder().build();\n }\n\n Map> userSessions = sessionEvents.get(key);\n\n ImmutableSet wordsInQuery =\n ImmutableSet.copyOf(query.toLowerCase(Locale.ROOT).split(\"\\\\s+\"));\n\n List matchingMemories = new ArrayList<>();\n\n for (List eventsInSession : userSessions.values()) {\n for (Event event : eventsInSession) {\n if (event.content().isEmpty() || event.content().get().parts().isEmpty()) {\n continue;\n }\n\n Set wordsInEvent = new HashSet<>();\n for (Part part : event.content().get().parts().get()) {\n if (!Strings.isNullOrEmpty(part.text().get())) {\n Matcher matcher = WORD_PATTERN.matcher(part.text().get());\n while (matcher.find()) {\n wordsInEvent.add(matcher.group().toLowerCase(Locale.ROOT));\n }\n }\n }\n\n if (wordsInEvent.isEmpty()) {\n continue;\n }\n\n if (!Collections.disjoint(wordsInQuery, wordsInEvent)) {\n MemoryEntry memory =\n MemoryEntry.builder()\n .setContent(event.content().get())\n .setAuthor(event.author())\n .setTimestamp(formatTimestamp(event.timestamp()))\n .build();\n matchingMemories.add(memory);\n }\n }\n }\n\n return SearchMemoryResponse.builder()\n .setMemories(ImmutableList.copyOf(matchingMemories))\n .build();\n });\n }\n\n private String formatTimestamp(long timestamp) {\n return Instant.ofEpochSecond(timestamp).toString();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/llmflows/AgentTransfer.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows.llmflows;\n\nimport com.google.adk.agents.BaseAgent;\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.agents.LlmAgent;\nimport com.google.adk.events.EventActions;\nimport com.google.adk.models.LlmRequest;\nimport com.google.adk.tools.FunctionTool;\nimport com.google.adk.tools.ToolContext;\nimport com.google.common.collect.ImmutableList;\nimport io.reactivex.rxjava3.core.Single;\nimport java.lang.reflect.Method;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/** {@link RequestProcessor} that handles agent transfer for LLM flow. */\npublic final class AgentTransfer implements RequestProcessor {\n\n public AgentTransfer() {}\n\n @Override\n public Single processRequest(\n InvocationContext context, LlmRequest request) {\n BaseAgent baseAgent = context.agent();\n if (!(baseAgent instanceof LlmAgent agent)) {\n throw new IllegalArgumentException(\n \"Base agent in InvocationContext is not an instance of Agent.\");\n }\n\n List transferTargets = getTransferTargets(agent);\n if (transferTargets.isEmpty()) {\n return Single.just(\n RequestProcessor.RequestProcessingResult.create(request, ImmutableList.of()));\n }\n\n LlmRequest.Builder builder =\n request.toBuilder()\n .appendInstructions(\n ImmutableList.of(buildTargetAgentsInstructions(agent, transferTargets)));\n Method transferToAgentMethod;\n try {\n transferToAgentMethod =\n AgentTransfer.class.getMethod(\"transferToAgent\", String.class, ToolContext.class);\n } catch (NoSuchMethodException e) {\n throw new IllegalStateException(e);\n }\n FunctionTool agentTransferTool = FunctionTool.create(transferToAgentMethod);\n agentTransferTool.processLlmRequest(builder, ToolContext.builder(context).build());\n return Single.just(\n RequestProcessor.RequestProcessingResult.create(builder.build(), ImmutableList.of()));\n }\n\n /** Builds a string with the target agent’s name and description. */\n private String buildTargetAgentsInfo(BaseAgent targetAgent) {\n return String.format(\n \"Agent name: %s\\nAgent description: %s\", targetAgent.name(), targetAgent.description());\n }\n\n /** Builds LLM instructions about when and how to transfer to another agent. */\n private String buildTargetAgentsInstructions(LlmAgent agent, List transferTargets) {\n StringBuilder sb = new StringBuilder();\n sb.append(\"You have a list of other agents to transfer to:\\n\");\n for (BaseAgent targetAgent : transferTargets) {\n sb.append(buildTargetAgentsInfo(targetAgent));\n sb.append(\"\\n\");\n }\n sb.append(\n \"If you are the best to answer the question according to your description, you can answer\"\n + \" it.\\n\");\n sb.append(\n \"If another agent is better for answering the question according to its description, call\"\n + \" `transferToAgent` function to transfer the question to that agent. When\"\n + \" transferring, do not generate any text other than the function call.\\n\");\n if (agent.parentAgent() != null) {\n sb.append(\"Your parent agent is \");\n sb.append(agent.parentAgent().name());\n sb.append(\n \".If neither the other agents nor you are best for answering the question according to\"\n + \" the descriptions, transfer to your parent agent. If you don't have parent agent,\"\n + \" try answer by yourself.\\n\");\n }\n return sb.toString();\n }\n\n /** Returns valid transfer targets: sub-agents, parent, and peers (if allowed). */\n private List getTransferTargets(LlmAgent agent) {\n List transferTargets = new ArrayList<>();\n transferTargets.addAll(agent.subAgents()); // Add all sub-agents\n\n BaseAgent parent = agent.parentAgent();\n // Agents eligible to transfer must have an LLM-based agent parent.\n if (!(parent instanceof LlmAgent)) {\n return transferTargets;\n }\n\n if (!agent.disallowTransferToParent()) {\n transferTargets.add(parent);\n }\n\n if (!agent.disallowTransferToPeers()) {\n for (BaseAgent peerAgent : parent.subAgents()) {\n if (!peerAgent.name().equals(agent.name())) {\n transferTargets.add(peerAgent);\n }\n }\n }\n\n return transferTargets;\n }\n\n /** Marks the target agent for transfer using the tool context. */\n public static void transferToAgent(String agentName, ToolContext toolContext) {\n EventActions eventActions = toolContext.eventActions();\n toolContext.setActions(eventActions.toBuilder().transferToAgent(agentName).build());\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/models/BaseLlm.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.models;\n\nimport io.reactivex.rxjava3.core.Flowable;\n\n/**\n * Abstract base class for Large Language Models (LLMs).\n *\n *

Provides a common interface for interacting with different LLMs.\n */\npublic abstract class BaseLlm {\n\n /** The name of the LLM model, e.g. gemini-1.5-flash or gemini-1.5-flash-001. */\n private final String model;\n\n public BaseLlm(String model) {\n this.model = model;\n }\n\n /**\n * Returns the name of the LLM model.\n *\n * @return The name of the LLM model.\n */\n public String model() {\n return model;\n }\n\n /**\n * Generates one content from the given LLM request and tools.\n *\n * @param llmRequest The LLM request containing the input prompt and parameters.\n * @param stream A boolean flag indicating whether to stream the response.\n * @return A Flowable of LlmResponses. For non-streaming calls, it will only yield one\n * LlmResponse. For streaming calls, it may yield more than one LlmResponse, but all yielded\n * LlmResponses should be treated as one content by merging their parts.\n */\n public abstract Flowable generateContent(LlmRequest llmRequest, boolean stream);\n\n /** Creates a live connection to the LLM. */\n public abstract BaseLlmConnection connect(LlmRequest llmRequest);\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/agents/LiveRequest.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.agents;\n\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.databind.annotation.JsonDeserialize;\nimport com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;\nimport com.google.adk.JsonBaseModel;\nimport com.google.auto.value.AutoValue;\nimport com.google.common.base.Preconditions;\nimport com.google.genai.types.Blob;\nimport com.google.genai.types.Content;\nimport java.util.Optional;\nimport javax.annotation.Nullable;\n\n/** Represents a request to be sent to a live connection to the LLM model. */\n@AutoValue\n@JsonDeserialize(builder = LiveRequest.Builder.class)\npublic abstract class LiveRequest extends JsonBaseModel {\n\n LiveRequest() {}\n\n /**\n * Returns the content of the request.\n *\n *

If set, send the content to the model in turn-by-turn mode.\n *\n * @return An optional {@link Content} object containing the content of the request.\n */\n @JsonProperty(\"content\")\n public abstract Optional content();\n\n /**\n * Returns the blob of the request.\n *\n *

If set, send the blob to the model in realtime mode.\n *\n * @return An optional {@link Blob} object containing the blob of the request.\n */\n @JsonProperty(\"blob\")\n public abstract Optional blob();\n\n /**\n * Returns whether the connection should be closed.\n *\n *

If set to true, the connection will be closed after the request is sent.\n *\n * @return A boolean indicating whether the connection should be closed.\n */\n @JsonProperty(\"close\")\n public abstract Optional close();\n\n /** Extracts boolean value from the close field or returns false if unset. */\n public boolean shouldClose() {\n return close().orElse(false);\n }\n\n /** Builder for constructing {@link LiveRequest} instances. */\n @AutoValue.Builder\n @JsonPOJOBuilder(buildMethodName = \"build\", withPrefix = \"\")\n public abstract static class Builder {\n @JsonProperty(\"content\")\n public abstract Builder content(@Nullable Content content);\n\n public abstract Builder content(Optional content);\n\n @JsonProperty(\"blob\")\n public abstract Builder blob(@Nullable Blob blob);\n\n public abstract Builder blob(Optional blob);\n\n @JsonProperty(\"close\")\n public abstract Builder close(@Nullable Boolean close);\n\n public abstract Builder close(Optional close);\n\n abstract LiveRequest autoBuild();\n\n public final LiveRequest build() {\n LiveRequest request = autoBuild();\n Preconditions.checkState(\n request.content().isPresent()\n || request.blob().isPresent()\n || request.close().isPresent(),\n \"One of content, blob, or close must be set\");\n return request;\n }\n }\n\n public static Builder builder() {\n return new AutoValue_LiveRequest.Builder().close(false);\n }\n\n public abstract Builder toBuilder();\n\n /** Deserializes a Json string to a {@link LiveRequest} object. */\n public static LiveRequest fromJsonString(String json) {\n return JsonBaseModel.fromJsonString(json, LiveRequest.class);\n }\n\n @JsonCreator\n static LiveRequest.Builder jacksonBuilder() {\n return LiveRequest.builder();\n }\n}\n"], ["/adk-java/dev/src/main/java/com/google/adk/web/AgentGraphGenerator.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.web;\n\nimport com.google.adk.agents.BaseAgent;\nimport com.google.adk.agents.LlmAgent;\nimport com.google.adk.tools.AgentTool;\nimport com.google.adk.tools.BaseTool;\nimport com.google.adk.tools.FunctionTool;\nimport com.google.adk.tools.retrieval.BaseRetrievalTool;\nimport guru.nidi.graphviz.attribute.Arrow;\nimport guru.nidi.graphviz.attribute.Color;\nimport guru.nidi.graphviz.attribute.Label;\nimport guru.nidi.graphviz.attribute.Rank;\nimport guru.nidi.graphviz.attribute.Shape;\nimport guru.nidi.graphviz.attribute.Style;\nimport guru.nidi.graphviz.engine.Format;\nimport guru.nidi.graphviz.engine.Graphviz;\nimport guru.nidi.graphviz.model.Factory;\nimport guru.nidi.graphviz.model.Link;\nimport guru.nidi.graphviz.model.MutableGraph;\nimport guru.nidi.graphviz.model.MutableNode;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.Set;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/** Utility class to generate Graphviz DOT representations of Agent structures. */\npublic class AgentGraphGenerator {\n\n private static final Logger log = LoggerFactory.getLogger(AgentGraphGenerator.class);\n\n private static final Color DARK_GREEN = Color.rgb(\"#0F5223\");\n private static final Color LIGHT_GREEN = Color.rgb(\"#69CB87\");\n private static final Color LIGHT_GRAY = Color.rgb(\"#CCCCCC\");\n private static final Color BG_COLOR = Color.rgb(\"#333537\");\n\n /**\n * Generates the DOT source string for the agent graph.\n *\n * @param rootAgent The root agent of the structure.\n * @param highlightPairs A list where each inner list contains two strings (fromNode, toNode)\n * representing an edge to highlight. Order matters for direction.\n * @return The DOT source string, or null if graph generation fails.\n */\n public static Optional getAgentGraphDotSource(\n BaseAgent rootAgent, List> highlightPairs) {\n log.debug(\n \"Building agent graph with root: {}, highlights: {}\", rootAgent.name(), highlightPairs);\n try {\n MutableGraph graph =\n Factory.mutGraph(\"AgentGraph\")\n .setDirected(true)\n .graphAttrs()\n .add(Rank.dir(Rank.RankDir.LEFT_TO_RIGHT), BG_COLOR.background());\n\n Set visitedNodes = new HashSet<>();\n buildGraphRecursive(graph, rootAgent, highlightPairs, visitedNodes);\n\n String dotSource = Graphviz.fromGraph(graph).render(Format.DOT).toString();\n log.debug(\"Generated DOT source successfully.\");\n return Optional.of(dotSource);\n } catch (Exception e) {\n log.error(\"Error generating agent graph DOT source\", e);\n return Optional.empty();\n }\n }\n\n /** Recursively builds the graph structure. */\n private static void buildGraphRecursive(\n MutableGraph graph,\n BaseAgent agent,\n List> highlightPairs,\n Set visitedNodes) {\n if (agent == null || visitedNodes.contains(getNodeName(agent))) {\n return;\n }\n\n drawNode(graph, agent, highlightPairs, visitedNodes);\n\n if (agent.subAgents() != null) {\n for (BaseAgent subAgent : agent.subAgents()) {\n if (subAgent != null) {\n drawEdge(graph, getNodeName(agent), getNodeName(subAgent), highlightPairs);\n buildGraphRecursive(graph, subAgent, highlightPairs, visitedNodes);\n }\n }\n }\n\n if (agent instanceof LlmAgent) {\n LlmAgent llmAgent = (LlmAgent) agent;\n List tools = llmAgent.canonicalTools().toList().blockingGet();\n if (tools != null) {\n for (BaseTool tool : tools) {\n if (tool != null) {\n drawNode(graph, tool, highlightPairs, visitedNodes);\n drawEdge(graph, getNodeName(agent), getNodeName(tool), highlightPairs);\n }\n }\n }\n }\n }\n\n /** Draws a node for an agent or tool, applying highlighting if applicable. */\n private static void drawNode(\n MutableGraph graph,\n Object toolOrAgent,\n List> highlightPairs,\n Set visitedNodes) {\n String name = getNodeName(toolOrAgent);\n if (name == null || name.isEmpty() || visitedNodes.contains(name)) {\n return;\n }\n\n Shape shape = getNodeShape(toolOrAgent);\n String caption = getNodeCaption(toolOrAgent);\n boolean isHighlighted = isNodeHighlighted(name, highlightPairs);\n\n MutableNode node =\n Factory.mutNode(name).add(Label.of(caption)).add(shape).add(LIGHT_GRAY.font());\n if (isHighlighted) {\n node.add(Style.FILLED);\n node.add(DARK_GREEN);\n } else {\n node.add(Style.ROUNDED);\n node.add(LIGHT_GRAY);\n }\n graph.add(node);\n visitedNodes.add(name);\n log.trace(\n \"Added node: name={}, caption={}, shape={}, highlighted={}\",\n name,\n caption,\n shape,\n isHighlighted);\n }\n\n /** Draws an edge between two nodes, applying highlighting if applicable. */\n private static void drawEdge(\n MutableGraph graph, String fromName, String toName, List> highlightPairs) {\n if (fromName == null || fromName.isEmpty() || toName == null || toName.isEmpty()) {\n log.warn(\n \"Skipping edge draw due to null or empty name: from='{}', to='{}'\", fromName, toName);\n return;\n }\n\n Optional highlightForward = isEdgeHighlighted(fromName, toName, highlightPairs);\n Link link = Factory.to(Factory.mutNode(toName));\n\n if (highlightForward.isPresent()) {\n link = link.with(LIGHT_GREEN);\n if (!highlightForward.get()) { // If true, means b->a was highlighted, draw reverse arrow\n link = link.with(Arrow.NORMAL.dir(Arrow.DirType.BACK));\n } else {\n link = link.with(Arrow.NORMAL);\n }\n } else {\n link = link.with(LIGHT_GRAY, Arrow.NONE);\n }\n\n graph.add(Factory.mutNode(fromName).addLink(link));\n log.trace(\n \"Added edge: from={}, to={}, highlighted={}\",\n fromName,\n toName,\n highlightForward.isPresent());\n }\n\n private static String getNodeName(Object toolOrAgent) {\n if (toolOrAgent instanceof BaseAgent) {\n return ((BaseAgent) toolOrAgent).name();\n } else if (toolOrAgent instanceof BaseTool) {\n return ((BaseTool) toolOrAgent).name();\n } else {\n log.warn(\"Unsupported type for getNodeName: {}\", toolOrAgent.getClass().getName());\n return \"unknown_\" + toolOrAgent.hashCode();\n }\n }\n\n private static String getNodeCaption(Object toolOrAgent) {\n String name = getNodeName(toolOrAgent); // Get name first\n if (toolOrAgent instanceof BaseAgent) {\n return \"🤖 \" + name;\n } else if (toolOrAgent instanceof BaseRetrievalTool) {\n return \"🔎 \" + name;\n } else if (toolOrAgent instanceof FunctionTool) {\n return \"🔧 \" + name;\n } else if (toolOrAgent instanceof AgentTool) {\n return \"🤖 \" + name;\n } else if (toolOrAgent instanceof BaseTool) {\n return \"🔧 \" + name;\n } else {\n log.warn(\"Unsupported type for getNodeCaption: {}\", toolOrAgent.getClass().getName());\n return \"❓ \" + name;\n }\n }\n\n private static Shape getNodeShape(Object toolOrAgent) {\n if (toolOrAgent instanceof BaseAgent) {\n return Shape.ELLIPSE;\n } else if (toolOrAgent instanceof BaseRetrievalTool) {\n return Shape.CYLINDER;\n } else if (toolOrAgent instanceof FunctionTool) {\n return Shape.BOX;\n } else if (toolOrAgent instanceof BaseTool) {\n return Shape.BOX;\n } else {\n log.warn(\"Unsupported type for getNodeShape: {}\", toolOrAgent.getClass().getName());\n return Shape.EGG;\n }\n }\n\n private static boolean isNodeHighlighted(String nodeName, List> highlightPairs) {\n if (highlightPairs == null || nodeName == null) {\n return false;\n }\n for (List pair : highlightPairs) {\n if (pair != null && pair.contains(nodeName)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Checks if an edge should be highlighted. Returns Optional: empty=no, true=forward,\n * false=backward\n */\n private static Optional isEdgeHighlighted(\n String fromName, String toName, List> highlightPairs) {\n if (highlightPairs == null || fromName == null || toName == null) {\n return Optional.empty();\n }\n for (List pair : highlightPairs) {\n if (pair != null && pair.size() == 2) {\n String pairFrom = pair.get(0);\n String pairTo = pair.get(1);\n if (fromName.equals(pairFrom) && toName.equals(pairTo)) {\n return Optional.of(true);\n }\n if (fromName.equals(pairTo) && toName.equals(pairFrom)) {\n return Optional.of(false);\n }\n }\n }\n return Optional.empty();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/llmflows/Instructions.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows.llmflows;\n\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.agents.LlmAgent;\nimport com.google.adk.agents.ReadonlyContext;\nimport com.google.adk.models.LlmRequest;\nimport com.google.adk.utils.InstructionUtils;\nimport com.google.common.collect.ImmutableList;\nimport io.reactivex.rxjava3.core.Single;\n\n/** {@link RequestProcessor} that handles instructions and global instructions for LLM flows. */\npublic final class Instructions implements RequestProcessor {\n public Instructions() {}\n\n @Override\n public Single processRequest(\n InvocationContext context, LlmRequest request) {\n if (!(context.agent() instanceof LlmAgent)) {\n return Single.error(\n new IllegalArgumentException(\n \"Agent in InvocationContext is not an instance of LlmAgent.\"));\n }\n LlmAgent agent = (LlmAgent) context.agent();\n ReadonlyContext readonlyContext = new ReadonlyContext(context);\n Single builderSingle = Single.just(request.toBuilder());\n if (agent.rootAgent() instanceof LlmAgent) {\n LlmAgent rootAgent = (LlmAgent) agent.rootAgent();\n builderSingle =\n builderSingle.flatMap(\n builder ->\n rootAgent\n .canonicalGlobalInstruction(readonlyContext)\n .flatMap(\n globalInstr -> {\n if (!globalInstr.isEmpty()) {\n return InstructionUtils.injectSessionState(context, globalInstr)\n .map(\n resolvedGlobalInstr ->\n builder.appendInstructions(\n ImmutableList.of(resolvedGlobalInstr)));\n }\n return Single.just(builder);\n }));\n }\n\n builderSingle =\n builderSingle.flatMap(\n builder ->\n agent\n .canonicalInstruction(readonlyContext)\n .flatMap(\n agentInstr -> {\n if (!agentInstr.isEmpty()) {\n return InstructionUtils.injectSessionState(context, agentInstr)\n .map(\n resolvedAgentInstr ->\n builder.appendInstructions(\n ImmutableList.of(resolvedAgentInstr)));\n }\n return Single.just(builder);\n }));\n\n return builderSingle.map(\n finalBuilder ->\n RequestProcessor.RequestProcessingResult.create(\n finalBuilder.build(), ImmutableList.of()));\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/agents/RunConfig.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.agents;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport com.google.genai.types.AudioTranscriptionConfig;\nimport com.google.genai.types.Modality;\nimport com.google.genai.types.SpeechConfig;\nimport org.jspecify.annotations.Nullable;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/** Configuration to modify an agent's LLM's underlying behavior. */\n@AutoValue\npublic abstract class RunConfig {\n private static final Logger logger = LoggerFactory.getLogger(RunConfig.class);\n\n /** Streaming mode for the runner. Required for BaseAgent.runLive() to work. */\n public enum StreamingMode {\n NONE,\n SSE,\n BIDI\n }\n\n public abstract @Nullable SpeechConfig speechConfig();\n\n public abstract ImmutableList responseModalities();\n\n public abstract boolean saveInputBlobsAsArtifacts();\n\n public abstract StreamingMode streamingMode();\n\n public abstract @Nullable AudioTranscriptionConfig outputAudioTranscription();\n\n public abstract int maxLlmCalls();\n\n public static Builder builder() {\n return new AutoValue_RunConfig.Builder()\n .setSaveInputBlobsAsArtifacts(false)\n .setResponseModalities(ImmutableList.of())\n .setStreamingMode(StreamingMode.NONE)\n .setMaxLlmCalls(500);\n }\n\n public static Builder builder(RunConfig runConfig) {\n return new AutoValue_RunConfig.Builder()\n .setSaveInputBlobsAsArtifacts(runConfig.saveInputBlobsAsArtifacts())\n .setStreamingMode(runConfig.streamingMode())\n .setMaxLlmCalls(runConfig.maxLlmCalls())\n .setResponseModalities(runConfig.responseModalities())\n .setSpeechConfig(runConfig.speechConfig())\n .setOutputAudioTranscription(runConfig.outputAudioTranscription());\n }\n\n /** Builder for {@link RunConfig}. */\n @AutoValue.Builder\n public abstract static class Builder {\n\n @CanIgnoreReturnValue\n public abstract Builder setSpeechConfig(SpeechConfig speechConfig);\n\n @CanIgnoreReturnValue\n public abstract Builder setResponseModalities(Iterable responseModalities);\n\n @CanIgnoreReturnValue\n public abstract Builder setSaveInputBlobsAsArtifacts(boolean saveInputBlobsAsArtifacts);\n\n @CanIgnoreReturnValue\n public abstract Builder setStreamingMode(StreamingMode streamingMode);\n\n @CanIgnoreReturnValue\n public abstract Builder setOutputAudioTranscription(\n AudioTranscriptionConfig outputAudioTranscription);\n\n @CanIgnoreReturnValue\n public abstract Builder setMaxLlmCalls(int maxLlmCalls);\n\n abstract RunConfig autoBuild();\n\n public RunConfig build() {\n RunConfig runConfig = autoBuild();\n if (runConfig.maxLlmCalls() < 0) {\n logger.warn(\n \"maxLlmCalls is negative. This will result in no enforcement on total\"\n + \" number of llm calls that will be made for a run. This may not be ideal, as this\"\n + \" could result in a never ending communication between the model and the agent in\"\n + \" certain cases.\");\n }\n return runConfig;\n }\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/FunctionCallingUtils.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools;\n\nimport static com.google.common.base.Preconditions.checkArgument;\n\nimport com.fasterxml.jackson.databind.BeanDescription;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition;\nimport com.google.adk.JsonBaseModel;\nimport com.google.common.base.Strings;\nimport com.google.genai.types.FunctionDeclaration;\nimport com.google.genai.types.Schema;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Parameter;\nimport java.lang.reflect.ParameterizedType;\nimport java.lang.reflect.Type;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\n\n/** Utility class for function calling. */\npublic final class FunctionCallingUtils {\n\n private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();\n\n public static FunctionDeclaration buildFunctionDeclaration(\n Method func, List ignoreParams) {\n String name =\n func.isAnnotationPresent(Annotations.Schema.class)\n && !func.getAnnotation(Annotations.Schema.class).name().isEmpty()\n ? func.getAnnotation(Annotations.Schema.class).name()\n : func.getName();\n FunctionDeclaration.Builder builder = FunctionDeclaration.builder().name(name);\n if (func.isAnnotationPresent(Annotations.Schema.class)\n && !func.getAnnotation(Annotations.Schema.class).description().isEmpty()) {\n builder.description(func.getAnnotation(Annotations.Schema.class).description());\n }\n List required = new ArrayList<>();\n Map properties = new LinkedHashMap<>();\n for (Parameter param : func.getParameters()) {\n String paramName =\n param.isAnnotationPresent(Annotations.Schema.class)\n && !param.getAnnotation(Annotations.Schema.class).name().isEmpty()\n ? param.getAnnotation(Annotations.Schema.class).name()\n : param.getName();\n if (ignoreParams.contains(paramName)) {\n continue;\n }\n required.add(paramName);\n properties.put(paramName, buildSchemaFromParameter(param));\n }\n builder.parameters(\n Schema.builder().required(required).properties(properties).type(\"OBJECT\").build());\n\n Type returnType = func.getGenericReturnType();\n if (returnType != Void.TYPE) {\n Type realReturnType = returnType;\n if (returnType instanceof ParameterizedType) {\n ParameterizedType parameterizedReturnType = (ParameterizedType) returnType;\n String returnTypeName = ((Class) parameterizedReturnType.getRawType()).getName();\n if (returnTypeName.equals(\"io.reactivex.rxjava3.core.Maybe\")\n || returnTypeName.equals(\"io.reactivex.rxjava3.core.Single\")) {\n returnType = parameterizedReturnType.getActualTypeArguments()[0];\n if (returnType instanceof ParameterizedType) {\n ParameterizedType maybeParameterizedType = (ParameterizedType) returnType;\n returnTypeName = ((Class) maybeParameterizedType.getRawType()).getName();\n }\n }\n if (returnTypeName.equals(\"java.util.Map\")\n || returnTypeName.equals(\"com.google.common.collect.ImmutableMap\")) {\n return builder.response(buildSchemaFromType(returnType)).build();\n }\n }\n throw new IllegalArgumentException(\n \"Return type should be Map or Maybe or Single, but it was \"\n + realReturnType.getTypeName());\n }\n return builder.build();\n }\n\n static FunctionDeclaration buildFunctionDeclaration(JsonBaseModel func, String description) {\n // Create function declaration through json string.\n String jsonString = func.toJson();\n checkArgument(!Strings.isNullOrEmpty(jsonString), \"Input String can't be null or empty.\");\n FunctionDeclaration declaration = FunctionDeclaration.fromJson(jsonString);\n declaration = declaration.toBuilder().description(description).build();\n if (declaration.name().isEmpty() || declaration.name().get().isEmpty()) {\n throw new IllegalArgumentException(\"name field must be present.\");\n }\n return declaration;\n }\n\n private static Schema buildSchemaFromParameter(Parameter param) {\n Schema.Builder builder = Schema.builder();\n if (param.isAnnotationPresent(Annotations.Schema.class)\n && !param.getAnnotation(Annotations.Schema.class).description().isEmpty()) {\n builder.description(param.getAnnotation(Annotations.Schema.class).description());\n }\n switch (param.getType().getName()) {\n case \"java.lang.String\" -> builder.type(\"STRING\");\n case \"boolean\", \"java.lang.Boolean\" -> builder.type(\"BOOLEAN\");\n case \"int\", \"java.lang.Integer\" -> builder.type(\"INTEGER\");\n case \"double\", \"java.lang.Double\", \"float\", \"java.lang.Float\", \"long\", \"java.lang.Long\" ->\n builder.type(\"NUMBER\");\n case \"java.util.List\" ->\n builder\n .type(\"ARRAY\")\n .items(\n buildSchemaFromType(\n ((ParameterizedType) param.getParameterizedType())\n .getActualTypeArguments()[0]));\n case \"java.util.Map\" -> builder.type(\"OBJECT\");\n default -> {\n BeanDescription beanDescription =\n OBJECT_MAPPER\n .getSerializationConfig()\n .introspect(OBJECT_MAPPER.constructType(param.getType()));\n Map properties = new LinkedHashMap<>();\n for (BeanPropertyDefinition property : beanDescription.findProperties()) {\n properties.put(property.getName(), buildSchemaFromType(property.getRawPrimaryType()));\n }\n builder.type(\"OBJECT\").properties(properties);\n }\n }\n return builder.build();\n }\n\n public static Schema buildSchemaFromType(Type type) {\n Schema.Builder builder = Schema.builder();\n if (type instanceof ParameterizedType parameterizedType) {\n switch (((Class) parameterizedType.getRawType()).getName()) {\n case \"java.util.List\" ->\n builder\n .type(\"ARRAY\")\n .items(buildSchemaFromType(parameterizedType.getActualTypeArguments()[0]));\n case \"java.util.Map\", \"com.google.common.collect.ImmutableMap\" -> builder.type(\"OBJECT\");\n default -> throw new IllegalArgumentException(\"Unsupported generic type: \" + type);\n }\n } else if (type instanceof Class clazz) {\n switch (clazz.getName()) {\n case \"java.lang.String\" -> builder.type(\"STRING\");\n case \"boolean\", \"java.lang.Boolean\" -> builder.type(\"BOOLEAN\");\n case \"int\", \"java.lang.Integer\" -> builder.type(\"INTEGER\");\n case \"double\", \"java.lang.Double\", \"float\", \"java.lang.Float\", \"long\", \"java.lang.Long\" ->\n builder.type(\"NUMBER\");\n case \"java.util.Map\", \"com.google.common.collect.ImmutableMap\" -> builder.type(\"OBJECT\");\n default -> {\n BeanDescription beanDescription =\n OBJECT_MAPPER.getSerializationConfig().introspect(OBJECT_MAPPER.constructType(type));\n Map properties = new LinkedHashMap<>();\n for (BeanPropertyDefinition property : beanDescription.findProperties()) {\n properties.put(property.getName(), buildSchemaFromType(property.getRawPrimaryType()));\n }\n builder.type(\"OBJECT\").properties(properties);\n }\n }\n }\n return builder.build();\n }\n\n private FunctionCallingUtils() {}\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/FunctionTool.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools;\n\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.genai.types.FunctionDeclaration;\nimport io.reactivex.rxjava3.core.Maybe;\nimport io.reactivex.rxjava3.core.Single;\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Modifier;\nimport java.lang.reflect.Parameter;\nimport java.lang.reflect.ParameterizedType;\nimport java.lang.reflect.Type;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\nimport javax.annotation.Nullable;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/** FunctionTool implements a customized function calling tool. */\npublic class FunctionTool extends BaseTool {\n private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();\n private static final Logger logger = LoggerFactory.getLogger(FunctionTool.class);\n\n @Nullable private final Object instance;\n private final Method func;\n private final FunctionDeclaration funcDeclaration;\n\n public static FunctionTool create(Object instance, Method func) {\n if (!areParametersAnnotatedWithSchema(func) && wasCompiledWithDefaultParameterNames(func)) {\n logger.error(\n \"Functions used in tools must have their parameters annotated with @Schema or at least\"\n + \" the code must be compiled with the -parameters flag as a fallback. Your function\"\n + \" tool will likely not work as expected and exit at runtime.\");\n }\n if (!Modifier.isStatic(func.getModifiers()) && !func.getDeclaringClass().isInstance(instance)) {\n throw new IllegalArgumentException(\n String.format(\n \"The instance provided is not an instance of the declaring class of the method.\"\n + \" Expected: %s, Actual: %s\",\n func.getDeclaringClass().getName(), instance.getClass().getName()));\n }\n return new FunctionTool(instance, func, /* isLongRunning= */ false);\n }\n\n public static FunctionTool create(Method func) {\n if (!areParametersAnnotatedWithSchema(func) && wasCompiledWithDefaultParameterNames(func)) {\n logger.error(\n \"Functions used in tools must have their parameters annotated with @Schema or at least\"\n + \" the code must be compiled with the -parameters flag as a fallback. Your function\"\n + \" tool will likely not work as expected and exit at runtime.\");\n }\n if (!Modifier.isStatic(func.getModifiers())) {\n throw new IllegalArgumentException(\"The method provided must be static.\");\n }\n return new FunctionTool(null, func, /* isLongRunning= */ false);\n }\n\n public static FunctionTool create(Class cls, String methodName) {\n for (Method method : cls.getMethods()) {\n if (method.getName().equals(methodName) && Modifier.isStatic(method.getModifiers())) {\n return create(null, method);\n }\n }\n throw new IllegalArgumentException(\n String.format(\"Static method %s not found in class %s.\", methodName, cls.getName()));\n }\n\n public static FunctionTool create(Object instance, String methodName) {\n Class cls = instance.getClass();\n for (Method method : cls.getMethods()) {\n if (method.getName().equals(methodName) && !Modifier.isStatic(method.getModifiers())) {\n return create(instance, method);\n }\n }\n throw new IllegalArgumentException(\n String.format(\"Instance method %s not found in class %s.\", methodName, cls.getName()));\n }\n\n private static boolean areParametersAnnotatedWithSchema(Method func) {\n for (Parameter parameter : func.getParameters()) {\n if (!parameter.isAnnotationPresent(Annotations.Schema.class)\n || parameter.getAnnotation(Annotations.Schema.class).name().isEmpty()) {\n return false;\n }\n }\n return true;\n }\n\n // Rough check to see if the code wasn't compiled with the -parameters flag.\n private static boolean wasCompiledWithDefaultParameterNames(Method func) {\n for (Parameter parameter : func.getParameters()) {\n String parameterName = parameter.getName();\n if (!parameterName.matches(\"arg\\\\d+\")) {\n return false;\n }\n }\n return true;\n }\n\n protected FunctionTool(@Nullable Object instance, Method func, boolean isLongRunning) {\n super(\n func.isAnnotationPresent(Annotations.Schema.class)\n && !func.getAnnotation(Annotations.Schema.class).name().isEmpty()\n ? func.getAnnotation(Annotations.Schema.class).name()\n : func.getName(),\n func.isAnnotationPresent(Annotations.Schema.class)\n ? func.getAnnotation(Annotations.Schema.class).description()\n : \"\",\n isLongRunning);\n boolean isStatic = Modifier.isStatic(func.getModifiers());\n if (isStatic && instance != null) {\n throw new IllegalArgumentException(\"Static function tool must not have an instance.\");\n } else if (!isStatic && instance == null) {\n throw new IllegalArgumentException(\"Instance function tool must have an instance.\");\n }\n\n this.instance = instance;\n this.func = func;\n this.funcDeclaration =\n FunctionCallingUtils.buildFunctionDeclaration(this.func, ImmutableList.of(\"toolContext\"));\n }\n\n @Override\n public Optional declaration() {\n return Optional.of(this.funcDeclaration);\n }\n\n @Override\n public Single> runAsync(Map args, ToolContext toolContext) {\n try {\n return this.call(args, toolContext).defaultIfEmpty(ImmutableMap.of());\n } catch (Exception e) {\n e.printStackTrace();\n return Single.just(ImmutableMap.of());\n }\n }\n\n @SuppressWarnings(\"unchecked\") // For tool parameter type casting.\n private Maybe> call(Map args, ToolContext toolContext)\n throws IllegalAccessException, InvocationTargetException {\n Parameter[] parameters = func.getParameters();\n Object[] arguments = new Object[parameters.length];\n for (int i = 0; i < parameters.length; i++) {\n String paramName =\n parameters[i].isAnnotationPresent(Annotations.Schema.class)\n && !parameters[i].getAnnotation(Annotations.Schema.class).name().isEmpty()\n ? parameters[i].getAnnotation(Annotations.Schema.class).name()\n : parameters[i].getName();\n if (paramName.equals(\"toolContext\")) {\n arguments[i] = toolContext;\n continue;\n }\n if (!args.containsKey(paramName)) {\n throw new IllegalArgumentException(\n String.format(\n \"The parameter '%s' was not found in the arguments provided by the model.\",\n paramName));\n }\n Class paramType = parameters[i].getType();\n Object argValue = args.get(paramName);\n if (paramType.equals(List.class)) {\n if (argValue instanceof List) {\n Type type =\n ((ParameterizedType) parameters[i].getParameterizedType())\n .getActualTypeArguments()[0];\n arguments[i] = createList((List) argValue, (Class) type);\n continue;\n }\n } else if (argValue instanceof Map) {\n arguments[i] = OBJECT_MAPPER.convertValue(argValue, paramType);\n continue;\n }\n arguments[i] = castValue(argValue, paramType);\n }\n Object result = func.invoke(instance, arguments);\n if (result == null) {\n return Maybe.empty();\n } else if (result instanceof Maybe) {\n return (Maybe>) result;\n } else if (result instanceof Single) {\n return ((Single>) result).toMaybe();\n } else {\n return Maybe.just((Map) result);\n }\n }\n\n private static List createList(List values, Class type) {\n List list = new ArrayList<>();\n // List of parameterized type is not supported.\n if (type == null) {\n return list;\n }\n Class cls = type;\n for (Object value : values) {\n if (cls == Integer.class\n || cls == Long.class\n || cls == Double.class\n || cls == Float.class\n || cls == Boolean.class\n || cls == String.class) {\n list.add(castValue(value, cls));\n } else {\n list.add(OBJECT_MAPPER.convertValue(value, type));\n }\n }\n return list;\n }\n\n private static Object castValue(Object value, Class type) {\n if (type.equals(Integer.class) || type.equals(int.class)) {\n if (value instanceof Integer) {\n return value;\n }\n }\n if (type.equals(Long.class) || type.equals(long.class)) {\n if (value instanceof Long || value instanceof Integer) {\n return value;\n }\n } else if (type.equals(Double.class) || type.equals(double.class)) {\n if (value instanceof Double d) {\n return d.doubleValue();\n }\n if (value instanceof Float f) {\n return f.doubleValue();\n }\n if (value instanceof Integer i) {\n return i.doubleValue();\n }\n if (value instanceof Long l) {\n return l.doubleValue();\n }\n } else if (type.equals(Float.class) || type.equals(float.class)) {\n if (value instanceof Double d) {\n return d.floatValue();\n }\n if (value instanceof Float f) {\n return f.floatValue();\n }\n if (value instanceof Integer i) {\n return i.floatValue();\n }\n if (value instanceof Long l) {\n return l.floatValue();\n }\n } else if (type.equals(Boolean.class) || type.equals(boolean.class)) {\n if (value instanceof Boolean) {\n return value;\n }\n } else if (type.equals(String.class)) {\n if (value instanceof String) {\n return value;\n }\n }\n return OBJECT_MAPPER.convertValue(value, type);\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/sessions/BaseSessionService.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\nimport com.google.adk.events.Event;\nimport com.google.adk.events.EventActions;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport io.reactivex.rxjava3.core.Completable;\nimport io.reactivex.rxjava3.core.Maybe;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.List;\nimport java.util.Objects;\nimport java.util.Optional;\nimport java.util.concurrent.ConcurrentMap;\nimport javax.annotation.Nullable;\n\n/**\n * Defines the contract for managing {@link Session}s and their associated {@link Event}s. Provides\n * methods for creating, retrieving, listing, and deleting sessions, as well as listing and\n * appending events to a session. Implementations of this interface handle the underlying storage\n * and retrieval logic.\n */\npublic interface BaseSessionService {\n\n /**\n * Creates a new session with the specified parameters.\n *\n * @param appName The name of the application associated with the session.\n * @param userId The identifier for the user associated with the session.\n * @param state An optional map representing the initial state of the session. Can be null or\n * empty.\n * @param sessionId An optional client-provided identifier for the session. If empty or null, the\n * service should generate a unique ID.\n * @return The newly created {@link Session} instance.\n * @throws SessionException if creation fails.\n */\n Single createSession(\n String appName,\n String userId,\n @Nullable ConcurrentMap state,\n @Nullable String sessionId);\n\n /**\n * Creates a new session with the specified application name and user ID, using a default state\n * (null) and allowing the service to generate a unique session ID.\n *\n *

This is a shortcut for {@link #createSession(String, String, Map, String)} with null state\n * and a null session ID.\n *\n * @param appName The name of the application associated with the session.\n * @param userId The identifier for the user associated with the session.\n * @return The newly created {@link Session} instance.\n * @throws SessionException if creation fails.\n */\n default Single createSession(String appName, String userId) {\n return createSession(appName, userId, null, null);\n }\n\n /**\n * Retrieves a specific session, optionally filtering the events included.\n *\n * @param appName The name of the application.\n * @param userId The identifier of the user.\n * @param sessionId The unique identifier of the session to retrieve.\n * @param config Optional configuration to filter the events returned within the session (e.g.,\n * limit number of recent events, filter by timestamp). If empty, default retrieval behavior\n * is used (potentially all events or a service-defined limit).\n * @return An {@link Optional} containing the {@link Session} if found, otherwise {@link\n * Optional#empty()}.\n * @throws SessionException for retrieval errors other than not found.\n */\n Maybe getSession(\n String appName, String userId, String sessionId, Optional config);\n\n /**\n * Lists sessions associated with a specific application and user.\n *\n *

The {@link Session} objects in the response typically contain only metadata (like ID,\n * creation time) and not the full event list or state to optimize performance.\n *\n * @param appName The name of the application.\n * @param userId The identifier of the user whose sessions are to be listed.\n * @return A {@link ListSessionsResponse} containing a list of matching sessions.\n * @throws SessionException if listing fails.\n */\n Single listSessions(String appName, String userId);\n\n /**\n * Deletes a specific session.\n *\n * @param appName The name of the application.\n * @param userId The identifier of the user.\n * @param sessionId The unique identifier of the session to delete.\n * @throws SessionNotFoundException if the session doesn't exist.\n * @throws SessionException for other deletion errors.\n */\n Completable deleteSession(String appName, String userId, String sessionId);\n\n /**\n * Lists the events within a specific session. Supports pagination via the response object.\n *\n * @param appName The name of the application.\n * @param userId The identifier of the user.\n * @param sessionId The unique identifier of the session whose events are to be listed.\n * @return A {@link ListEventsResponse} containing a list of events and an optional token for\n * retrieving the next page.\n * @throws SessionNotFoundException if the session doesn't exist.\n * @throws SessionException for other listing errors.\n */\n Single listEvents(String appName, String userId, String sessionId);\n\n /**\n * Closes a session. This is currently a placeholder and may involve finalizing session state or\n * performing cleanup actions in future implementations. The default implementation does nothing.\n *\n * @param session The session object to close.\n */\n default Completable closeSession(Session session) {\n // Default implementation does nothing.\n // TODO: Determine whether we want to finalize the session here.\n return Completable.complete();\n }\n\n /**\n * Appends an event to an in-memory session object and updates the session's state based on the\n * event's state delta, if applicable.\n *\n *

This method primarily modifies the passed {@code session} object in memory. Persisting these\n * changes typically requires a separate call to an update/save method provided by the specific\n * service implementation, or might happen implicitly depending on the implementation's design.\n *\n *

If the event is marked as partial (e.g., {@code event.isPartial() == true}), it is returned\n * directly without modifying the session state or event list. State delta keys starting with\n * {@link State#TEMP_PREFIX} are ignored during state updates.\n *\n * @param session The {@link Session} object to which the event should be appended (will be\n * mutated).\n * @param event The {@link Event} to append.\n * @return The appended {@link Event} instance (or the original event if it was partial).\n * @throws NullPointerException if session or event is null.\n */\n @CanIgnoreReturnValue\n default Single appendEvent(Session session, Event event) {\n Objects.requireNonNull(session, \"session cannot be null\");\n Objects.requireNonNull(event, \"event cannot be null\");\n\n // If the event indicates it's partial or incomplete, don't process it yet.\n if (event.partial().orElse(false)) {\n return Single.just(event);\n }\n\n EventActions actions = event.actions();\n if (actions != null) {\n ConcurrentMap stateDelta = actions.stateDelta();\n if (stateDelta != null && !stateDelta.isEmpty()) {\n ConcurrentMap sessionState = session.state();\n if (sessionState != null) {\n stateDelta.forEach(\n (key, value) -> {\n if (!key.startsWith(State.TEMP_PREFIX)) {\n sessionState.put(key, value);\n }\n });\n }\n }\n }\n\n List sessionEvents = session.events();\n if (sessionEvents != null) {\n sessionEvents.add(event);\n }\n\n return Single.just(event);\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/artifacts/InMemoryArtifactService.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.artifacts;\n\nimport static com.google.common.collect.ImmutableList.toImmutableList;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Streams;\nimport com.google.genai.types.Part;\nimport io.reactivex.rxjava3.core.Completable;\nimport io.reactivex.rxjava3.core.Maybe;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.stream.IntStream;\n\n/** An in-memory implementation of the {@link BaseArtifactService}. */\npublic final class InMemoryArtifactService implements BaseArtifactService {\n private final Map>>>> artifacts;\n\n public InMemoryArtifactService() {\n this.artifacts = new HashMap<>();\n }\n\n /**\n * Saves an artifact in memory and assigns a new version.\n *\n * @return Single with assigned version number.\n */\n @Override\n public Single saveArtifact(\n String appName, String userId, String sessionId, String filename, Part artifact) {\n List versions =\n artifacts\n .computeIfAbsent(appName, k -> new HashMap<>())\n .computeIfAbsent(userId, k -> new HashMap<>())\n .computeIfAbsent(sessionId, k -> new HashMap<>())\n .computeIfAbsent(filename, k -> new ArrayList<>());\n versions.add(artifact);\n return Single.just(versions.size() - 1);\n }\n\n /**\n * Loads an artifact by version or latest.\n *\n * @return Maybe with the artifact, or empty if not found.\n */\n @Override\n public Maybe loadArtifact(\n String appName, String userId, String sessionId, String filename, Optional version) {\n List versions =\n artifacts\n .getOrDefault(appName, new HashMap<>())\n .getOrDefault(userId, new HashMap<>())\n .getOrDefault(sessionId, new HashMap<>())\n .getOrDefault(filename, new ArrayList<>());\n\n if (versions.isEmpty()) {\n return Maybe.empty();\n }\n if (version.isPresent()) {\n int v = version.get();\n if (v >= 0 && v < versions.size()) {\n return Maybe.just(versions.get(v));\n } else {\n return Maybe.empty();\n }\n } else {\n return Maybe.fromOptional(Streams.findLast(versions.stream()));\n }\n }\n\n /**\n * Lists filenames of stored artifacts for the session.\n *\n * @return Single with list of artifact filenames.\n */\n @Override\n public Single listArtifactKeys(\n String appName, String userId, String sessionId) {\n return Single.just(\n ListArtifactsResponse.builder()\n .filenames(\n ImmutableList.copyOf(\n artifacts\n .getOrDefault(appName, new HashMap<>())\n .getOrDefault(userId, new HashMap<>())\n .getOrDefault(sessionId, new HashMap<>())\n .keySet()))\n .build());\n }\n\n /**\n * Deletes all versions of the given artifact.\n *\n * @return Completable indicating completion.\n */\n @Override\n public Completable deleteArtifact(\n String appName, String userId, String sessionId, String filename) {\n artifacts\n .getOrDefault(appName, new HashMap<>())\n .getOrDefault(userId, new HashMap<>())\n .getOrDefault(sessionId, new HashMap<>())\n .remove(filename);\n return Completable.complete();\n }\n\n /**\n * Lists all versions of the specified artifact.\n *\n * @return Single with list of version numbers.\n */\n @Override\n public Single> listVersions(\n String appName, String userId, String sessionId, String filename) {\n int size =\n artifacts\n .getOrDefault(appName, new HashMap<>())\n .getOrDefault(userId, new HashMap<>())\n .getOrDefault(sessionId, new HashMap<>())\n .getOrDefault(filename, new ArrayList<>())\n .size();\n if (size == 0) {\n return Single.just(ImmutableList.of());\n }\n return Single.just(IntStream.range(0, size).boxed().collect(toImmutableList()));\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/llmflows/Examples.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows.llmflows;\n\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.agents.LlmAgent;\nimport com.google.adk.examples.ExampleUtils;\nimport com.google.adk.models.LlmRequest;\nimport com.google.common.collect.ImmutableList;\nimport io.reactivex.rxjava3.core.Single;\n\n/** {@link RequestProcessor} that populates examples in LLM request. */\npublic final class Examples implements RequestProcessor {\n\n public Examples() {}\n\n @Override\n public Single processRequest(\n InvocationContext context, LlmRequest request) {\n if (!(context.agent() instanceof LlmAgent)) {\n throw new IllegalArgumentException(\"Agent in InvocationContext is not an instance of Agent.\");\n }\n LlmAgent agent = (LlmAgent) context.agent();\n LlmRequest.Builder builder = request.toBuilder();\n\n String query =\n context.userContent().isPresent()\n ? context.userContent().get().parts().get().get(0).text().orElse(\"\")\n : \"\";\n agent\n .exampleProvider()\n .ifPresent(\n exampleProvider ->\n builder.appendInstructions(\n ImmutableList.of(ExampleUtils.buildExampleSi(exampleProvider, query))));\n return Single.just(\n RequestProcessor.RequestProcessingResult.create(builder.build(), ImmutableList.of()));\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/applicationintegrationtoolset/ApplicationIntegrationToolset.java", "package com.google.adk.tools.applicationintegrationtoolset;\n\nimport static com.google.common.base.Strings.isNullOrEmpty;\n\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.fasterxml.jackson.databind.node.ObjectNode;\nimport com.google.adk.agents.ReadonlyContext;\nimport com.google.adk.tools.BaseTool;\nimport com.google.adk.tools.BaseToolset;\nimport com.google.adk.tools.applicationintegrationtoolset.IntegrationConnectorTool.DefaultHttpExecutor;\nimport com.google.adk.tools.applicationintegrationtoolset.IntegrationConnectorTool.HttpExecutor;\nimport io.reactivex.rxjava3.core.Flowable;\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport org.jspecify.annotations.Nullable;\n\n/** Application Integration Toolset */\npublic class ApplicationIntegrationToolset implements BaseToolset {\n String project;\n String location;\n @Nullable String integration;\n @Nullable List triggers;\n @Nullable String connection;\n @Nullable Map> entityOperations;\n @Nullable List actions;\n String serviceAccountJson;\n @Nullable String toolNamePrefix;\n @Nullable String toolInstructions;\n public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();\n HttpExecutor httpExecutor;\n\n /**\n * ApplicationIntegrationToolset generates tools from a given Application Integration resource.\n *\n *

Example Usage:\n *\n *

integrationTool = new ApplicationIntegrationToolset( project=\"test-project\",\n * location=\"us-central1\", integration=\"test-integration\",\n * triggers=ImmutableList.of(\"api_trigger/test_trigger\", \"api_trigger/test_trigger_2\",\n * serviceAccountJson=\"{....}\"),connection=null,enitityOperations=null,actions=null,toolNamePrefix=\"test-integration-tool\",toolInstructions=\"This\n * tool is used to get response from test-integration.\");\n *\n *

connectionTool = new ApplicationIntegrationToolset( project=\"test-project\",\n * location=\"us-central1\", integration=null, triggers=null, connection=\"test-connection\",\n * entityOperations=ImmutableMap.of(\"Entity1\", ImmutableList.of(\"LIST\", \"GET\", \"UPDATE\")),\n * \"Entity2\", ImmutableList.of()), actions=ImmutableList.of(\"ExecuteCustomQuery\"),\n * serviceAccountJson=\"{....}\", toolNamePrefix=\"test-tool\", toolInstructions=\"This tool is used to\n * list, get and update issues in Jira.\");\n *\n * @param project The GCP project ID.\n * @param location The GCP location of integration.\n * @param integration The integration name.\n * @param triggers(Optional) The list of trigger ids in the integration.\n * @param connection(Optional) The connection name.\n * @param entityOperations(Optional) The entity operations.\n * @param actions(Optional) The actions.\n * @param serviceAccountJson(Optional) The service account configuration as a dictionary. Required\n * if not using default service credential. Used for fetching the Application Integration or\n * Integration Connector resource.\n * @param toolNamePrefix(Optional) The tool name prefix.\n * @param toolInstructions(Optional) The tool instructions.\n */\n public ApplicationIntegrationToolset(\n String project,\n String location,\n String integration,\n List triggers,\n String connection,\n Map> entityOperations,\n List actions,\n String serviceAccountJson,\n String toolNamePrefix,\n String toolInstructions) {\n this(\n project,\n location,\n integration,\n triggers,\n connection,\n entityOperations,\n actions,\n serviceAccountJson,\n toolNamePrefix,\n toolInstructions,\n new DefaultHttpExecutor().createExecutor(serviceAccountJson));\n }\n\n ApplicationIntegrationToolset(\n String project,\n String location,\n String integration,\n List triggers,\n String connection,\n Map> entityOperations,\n List actions,\n String serviceAccountJson,\n String toolNamePrefix,\n String toolInstructions,\n HttpExecutor httpExecutor) {\n this.project = project;\n this.location = location;\n this.integration = integration;\n this.triggers = triggers;\n this.connection = connection;\n this.entityOperations = entityOperations;\n this.actions = actions;\n this.serviceAccountJson = serviceAccountJson;\n this.toolNamePrefix = toolNamePrefix;\n this.toolInstructions = toolInstructions;\n this.httpExecutor = httpExecutor;\n }\n\n List getPathUrl(String openApiSchemaString) throws Exception {\n List pathUrls = new ArrayList<>();\n JsonNode topLevelNode = OBJECT_MAPPER.readTree(openApiSchemaString);\n JsonNode specNode = topLevelNode.path(\"openApiSpec\");\n if (specNode.isMissingNode() || !specNode.isTextual()) {\n throw new IllegalArgumentException(\n \"Failed to get OpenApiSpec, please check the project and region for the integration.\");\n }\n JsonNode rootNode = OBJECT_MAPPER.readTree(specNode.asText());\n JsonNode pathsNode = rootNode.path(\"paths\");\n Iterator> paths = pathsNode.fields();\n while (paths.hasNext()) {\n Map.Entry pathEntry = paths.next();\n String pathUrl = pathEntry.getKey();\n pathUrls.add(pathUrl);\n }\n return pathUrls;\n }\n\n private List getAllTools() throws Exception {\n String openApiSchemaString = null;\n List tools = new ArrayList<>();\n if (!isNullOrEmpty(this.integration)) {\n IntegrationClient integrationClient =\n new IntegrationClient(\n this.project,\n this.location,\n this.integration,\n this.triggers,\n null,\n null,\n null,\n this.httpExecutor);\n openApiSchemaString = integrationClient.generateOpenApiSpec();\n List pathUrls = getPathUrl(openApiSchemaString);\n for (String pathUrl : pathUrls) {\n String toolName = integrationClient.getOperationIdFromPathUrl(openApiSchemaString, pathUrl);\n if (toolName != null) {\n tools.add(\n new IntegrationConnectorTool(\n openApiSchemaString,\n pathUrl,\n toolName,\n toolInstructions,\n null,\n null,\n null,\n this.serviceAccountJson,\n this.httpExecutor));\n }\n }\n } else if (!isNullOrEmpty(this.connection)\n && (this.entityOperations != null || this.actions != null)) {\n IntegrationClient integrationClient =\n new IntegrationClient(\n this.project,\n this.location,\n null,\n null,\n this.connection,\n this.entityOperations,\n this.actions,\n this.httpExecutor);\n ObjectNode parentOpenApiSpec = OBJECT_MAPPER.createObjectNode();\n ObjectNode openApiSpec =\n integrationClient.getOpenApiSpecForConnection(toolNamePrefix, toolInstructions);\n String openApiSpecString = OBJECT_MAPPER.writeValueAsString(openApiSpec);\n parentOpenApiSpec.put(\"openApiSpec\", openApiSpecString);\n openApiSchemaString = OBJECT_MAPPER.writeValueAsString(parentOpenApiSpec);\n List pathUrls = getPathUrl(openApiSchemaString);\n for (String pathUrl : pathUrls) {\n String toolName = integrationClient.getOperationIdFromPathUrl(openApiSchemaString, pathUrl);\n if (!isNullOrEmpty(toolName)) {\n ConnectionsClient connectionsClient =\n new ConnectionsClient(\n this.project, this.location, this.connection, this.httpExecutor, OBJECT_MAPPER);\n ConnectionsClient.ConnectionDetails connectionDetails =\n connectionsClient.getConnectionDetails();\n\n tools.add(\n new IntegrationConnectorTool(\n openApiSchemaString,\n pathUrl,\n toolName,\n \"\",\n connectionDetails.name,\n connectionDetails.serviceName,\n connectionDetails.host,\n this.serviceAccountJson,\n this.httpExecutor));\n }\n }\n } else {\n throw new IllegalArgumentException(\n \"Invalid request, Either integration or (connection and\"\n + \" (entityOperations or actions)) should be provided.\");\n }\n\n return tools;\n }\n\n @Override\n public Flowable getTools(@Nullable ReadonlyContext readonlyContext) {\n try {\n List allTools = getAllTools();\n return Flowable.fromIterable(allTools);\n } catch (Exception e) {\n return Flowable.error(e);\n }\n }\n\n @Override\n public void close() throws Exception {\n // Nothing to close.\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/mcp/DefaultMcpTransportBuilder.java", "package com.google.adk.tools.mcp;\n\nimport com.google.common.collect.ImmutableMap;\nimport io.modelcontextprotocol.client.transport.HttpClientSseClientTransport;\nimport io.modelcontextprotocol.client.transport.ServerParameters;\nimport io.modelcontextprotocol.client.transport.StdioClientTransport;\nimport io.modelcontextprotocol.spec.McpClientTransport;\nimport java.util.Collection;\nimport java.util.Optional;\n\n/**\n * The default builder for creating MCP client transports. Supports StdioClientTransport based on\n * {@link ServerParameters} and the standard HttpClientSseClientTransport based on {@link\n * SseServerParameters}.\n */\npublic class DefaultMcpTransportBuilder implements McpTransportBuilder {\n\n @Override\n public McpClientTransport build(Object connectionParams) {\n if (connectionParams instanceof ServerParameters serverParameters) {\n return new StdioClientTransport(serverParameters);\n } else if (connectionParams instanceof SseServerParameters sseServerParams) {\n return HttpClientSseClientTransport.builder(sseServerParams.url())\n .sseEndpoint(\"sse\")\n .customizeRequest(\n builder ->\n Optional.ofNullable(sseServerParams.headers())\n .map(ImmutableMap::entrySet)\n .stream()\n .flatMap(Collection::stream)\n .forEach(\n entry ->\n builder.header(\n entry.getKey(),\n Optional.ofNullable(entry.getValue())\n .map(Object::toString)\n .orElse(\"\"))))\n .build();\n } else {\n throw new IllegalArgumentException(\n \"DefaultMcpTransportBuilder supports only ServerParameters or SseServerParameters, but\"\n + \" got \"\n + connectionParams.getClass().getName());\n }\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/agents/Callbacks.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.agents;\n\nimport com.google.adk.models.LlmRequest;\nimport com.google.adk.models.LlmResponse;\nimport com.google.adk.tools.BaseTool;\nimport com.google.adk.tools.ToolContext;\nimport com.google.genai.types.Content;\nimport io.reactivex.rxjava3.core.Maybe;\nimport java.util.Map;\nimport java.util.Optional;\n\n/** Functional interfaces for agent lifecycle callbacks. */\npublic final class Callbacks {\n\n interface BeforeModelCallbackBase {}\n\n @FunctionalInterface\n public interface BeforeModelCallback extends BeforeModelCallbackBase {\n /**\n * Async callback before LLM invocation.\n *\n * @param callbackContext Callback context.\n * @param llmRequest LLM request.\n * @return response override, or empty to continue.\n */\n Maybe call(CallbackContext callbackContext, LlmRequest llmRequest);\n }\n\n /**\n * Helper interface to allow for sync beforeModelCallback. The function is wrapped into an async\n * one before being processed further.\n */\n @FunctionalInterface\n public interface BeforeModelCallbackSync extends BeforeModelCallbackBase {\n Optional call(CallbackContext callbackContext, LlmRequest llmRequest);\n }\n\n interface AfterModelCallbackBase {}\n\n @FunctionalInterface\n public interface AfterModelCallback extends AfterModelCallbackBase {\n /**\n * Async callback after LLM response.\n *\n * @param callbackContext Callback context.\n * @param llmResponse LLM response.\n * @return modified response, or empty to keep original.\n */\n Maybe call(CallbackContext callbackContext, LlmResponse llmResponse);\n }\n\n /**\n * Helper interface to allow for sync afterModelCallback. The function is wrapped into an async\n * one before being processed further.\n */\n @FunctionalInterface\n public interface AfterModelCallbackSync extends AfterModelCallbackBase {\n Optional call(CallbackContext callbackContext, LlmResponse llmResponse);\n }\n\n interface BeforeAgentCallbackBase {}\n\n @FunctionalInterface\n public interface BeforeAgentCallback extends BeforeAgentCallbackBase {\n /**\n * Async callback before agent runs.\n *\n * @param callbackContext Callback context.\n * @return content override, or empty to continue.\n */\n Maybe call(CallbackContext callbackContext);\n }\n\n /**\n * Helper interface to allow for sync beforeAgentCallback. The function is wrapped into an async\n * one before being processed further.\n */\n @FunctionalInterface\n public interface BeforeAgentCallbackSync extends BeforeAgentCallbackBase {\n Optional call(CallbackContext callbackContext);\n }\n\n interface AfterAgentCallbackBase {}\n\n @FunctionalInterface\n public interface AfterAgentCallback extends AfterAgentCallbackBase {\n /**\n * Async callback after agent runs.\n *\n * @param callbackContext Callback context.\n * @return modified content, or empty to keep original.\n */\n Maybe call(CallbackContext callbackContext);\n }\n\n /**\n * Helper interface to allow for sync afterAgentCallback. The function is wrapped into an async\n * one before being processed further.\n */\n @FunctionalInterface\n public interface AfterAgentCallbackSync extends AfterAgentCallbackBase {\n Optional call(CallbackContext callbackContext);\n }\n\n interface BeforeToolCallbackBase {}\n\n @FunctionalInterface\n public interface BeforeToolCallback extends BeforeToolCallbackBase {\n /**\n * Async callback before tool runs.\n *\n * @param invocationContext Invocation context.\n * @param baseTool Tool instance.\n * @param input Tool input arguments.\n * @param toolContext Tool context.\n * @return override result, or empty to continue.\n */\n Maybe> call(\n InvocationContext invocationContext,\n BaseTool baseTool,\n Map input,\n ToolContext toolContext);\n }\n\n /**\n * Helper interface to allow for sync beforeToolCallback. The function is wrapped into an async\n * one before being processed further.\n */\n @FunctionalInterface\n public interface BeforeToolCallbackSync extends BeforeToolCallbackBase {\n Optional> call(\n InvocationContext invocationContext,\n BaseTool baseTool,\n Map input,\n ToolContext toolContext);\n }\n\n interface AfterToolCallbackBase {}\n\n @FunctionalInterface\n public interface AfterToolCallback extends AfterToolCallbackBase {\n /**\n * Async callback after tool runs.\n *\n * @param invocationContext Invocation context.\n * @param baseTool Tool instance.\n * @param input Tool input arguments.\n * @param toolContext Tool context.\n * @param response Raw tool response.\n * @return processed result, or empty to keep original.\n */\n Maybe> call(\n InvocationContext invocationContext,\n BaseTool baseTool,\n Map input,\n ToolContext toolContext,\n Object response);\n }\n\n /**\n * Helper interface to allow for sync afterToolCallback. The function is wrapped into an async one\n * before being processed further.\n */\n @FunctionalInterface\n public interface AfterToolCallbackSync extends AfterToolCallbackBase {\n Optional> call(\n InvocationContext invocationContext,\n BaseTool baseTool,\n Map input,\n ToolContext toolContext,\n Object response);\n }\n\n private Callbacks() {}\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/agents/ParallelAgent.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.agents;\n\nimport static com.google.common.base.Strings.isNullOrEmpty;\n\nimport com.google.adk.events.Event;\nimport com.google.common.collect.ImmutableList;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport io.reactivex.rxjava3.core.Flowable;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * A shell agent that runs its sub-agents in parallel in isolated manner.\n *\n *

This approach is beneficial for scenarios requiring multiple perspectives or attempts on a\n * single task, such as running different algorithms simultaneously or generating multiple responses\n * for review by a subsequent evaluation agent.\n */\npublic class ParallelAgent extends BaseAgent {\n\n /**\n * Constructor for ParallelAgent.\n *\n * @param name The agent's name.\n * @param description The agent's description.\n * @param subAgents The list of sub-agents to run sequentially.\n * @param beforeAgentCallback Optional callback before the agent runs.\n * @param afterAgentCallback Optional callback after the agent runs.\n */\n private ParallelAgent(\n String name,\n String description,\n List subAgents,\n List beforeAgentCallback,\n List afterAgentCallback) {\n\n super(name, description, subAgents, beforeAgentCallback, afterAgentCallback);\n }\n\n /** Builder for {@link ParallelAgent}. */\n public static class Builder {\n private String name;\n private String description;\n private List subAgents;\n private ImmutableList beforeAgentCallback;\n private ImmutableList afterAgentCallback;\n\n @CanIgnoreReturnValue\n public Builder name(String name) {\n this.name = name;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder description(String description) {\n this.description = description;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder subAgents(List subAgents) {\n this.subAgents = subAgents;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder subAgents(BaseAgent... subAgents) {\n this.subAgents = ImmutableList.copyOf(subAgents);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeAgentCallback(Callbacks.BeforeAgentCallback beforeAgentCallback) {\n this.beforeAgentCallback = ImmutableList.of(beforeAgentCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeAgentCallback(\n List beforeAgentCallback) {\n this.beforeAgentCallback = CallbackUtil.getBeforeAgentCallbacks(beforeAgentCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterAgentCallback(Callbacks.AfterAgentCallback afterAgentCallback) {\n this.afterAgentCallback = ImmutableList.of(afterAgentCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterAgentCallback(List afterAgentCallback) {\n this.afterAgentCallback = CallbackUtil.getAfterAgentCallbacks(afterAgentCallback);\n return this;\n }\n\n public ParallelAgent build() {\n return new ParallelAgent(\n name, description, subAgents, beforeAgentCallback, afterAgentCallback);\n }\n }\n\n public static Builder builder() {\n return new Builder();\n }\n\n /**\n * Sets the branch for the current agent in the invocation context.\n *\n *

Appends the agent name to the current branch, or sets it if undefined.\n *\n * @param currentAgent Current agent.\n * @param invocationContext Invocation context to update.\n */\n private static void setBranchForCurrentAgent(\n BaseAgent currentAgent, InvocationContext invocationContext) {\n String branch = invocationContext.branch().orElse(null);\n if (isNullOrEmpty(branch)) {\n invocationContext.branch(currentAgent.name());\n } else {\n invocationContext.branch(branch + \".\" + currentAgent.name());\n }\n }\n\n /**\n * Runs sub-agents in parallel and emits their events.\n *\n *

Sets the branch and merges event streams from all sub-agents.\n *\n * @param invocationContext Invocation context.\n * @return Flowable emitting events from all sub-agents.\n */\n @Override\n protected Flowable runAsyncImpl(InvocationContext invocationContext) {\n setBranchForCurrentAgent(this, invocationContext);\n\n List currentSubAgents = subAgents();\n if (currentSubAgents == null || currentSubAgents.isEmpty()) {\n return Flowable.empty();\n }\n\n List> agentFlowables = new ArrayList<>();\n for (BaseAgent subAgent : currentSubAgents) {\n agentFlowables.add(subAgent.runAsync(invocationContext));\n }\n return Flowable.merge(agentFlowables);\n }\n\n /**\n * Not supported for ParallelAgent.\n *\n * @param invocationContext Invocation context.\n * @return Flowable that always throws UnsupportedOperationException.\n */\n @Override\n protected Flowable runLiveImpl(InvocationContext invocationContext) {\n return Flowable.error(\n new UnsupportedOperationException(\"runLive is not defined for ParallelAgent yet.\"));\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/agents/LoopAgent.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.agents;\n\nimport com.google.adk.events.Event;\nimport com.google.common.collect.ImmutableList;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport io.reactivex.rxjava3.core.Flowable;\nimport java.util.List;\nimport java.util.Optional;\n\n/**\n * An agent that runs its sub-agents sequentially in a loop.\n *\n *

The loop continues until a sub-agent escalates, or until the maximum number of iterations is\n * reached (if specified).\n */\npublic class LoopAgent extends BaseAgent {\n\n private final Optional maxIterations;\n\n /**\n * Constructor for LoopAgent.\n *\n * @param name The agent's name.\n * @param description The agent's description.\n * @param subAgents The list of sub-agents to run in the loop.\n * @param maxIterations Optional termination condition: maximum number of loop iterations.\n * @param beforeAgentCallback Optional callback before the agent runs.\n * @param afterAgentCallback Optional callback after the agent runs.\n */\n private LoopAgent(\n String name,\n String description,\n List subAgents,\n Optional maxIterations,\n List beforeAgentCallback,\n List afterAgentCallback) {\n\n super(name, description, subAgents, beforeAgentCallback, afterAgentCallback);\n this.maxIterations = maxIterations;\n }\n\n /** Builder for {@link LoopAgent}. */\n public static class Builder {\n private String name;\n private String description;\n private List subAgents;\n private Optional maxIterations = Optional.empty();\n private ImmutableList beforeAgentCallback;\n private ImmutableList afterAgentCallback;\n\n @CanIgnoreReturnValue\n public Builder name(String name) {\n this.name = name;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder description(String description) {\n this.description = description;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder subAgents(List subAgents) {\n this.subAgents = subAgents;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder subAgents(BaseAgent... subAgents) {\n this.subAgents = ImmutableList.copyOf(subAgents);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder maxIterations(int maxIterations) {\n this.maxIterations = Optional.of(maxIterations);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder maxIterations(Optional maxIterations) {\n this.maxIterations = maxIterations;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeAgentCallback(Callbacks.BeforeAgentCallback beforeAgentCallback) {\n this.beforeAgentCallback = ImmutableList.of(beforeAgentCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeAgentCallback(\n List beforeAgentCallback) {\n this.beforeAgentCallback = CallbackUtil.getBeforeAgentCallbacks(beforeAgentCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterAgentCallback(Callbacks.AfterAgentCallback afterAgentCallback) {\n this.afterAgentCallback = ImmutableList.of(afterAgentCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterAgentCallback(List afterAgentCallback) {\n this.afterAgentCallback = CallbackUtil.getAfterAgentCallbacks(afterAgentCallback);\n return this;\n }\n\n public LoopAgent build() {\n // TODO(b/410859954): Add validation for required fields like name.\n return new LoopAgent(\n name, description, subAgents, maxIterations, beforeAgentCallback, afterAgentCallback);\n }\n }\n\n public static Builder builder() {\n return new Builder();\n }\n\n @Override\n protected Flowable runAsyncImpl(InvocationContext invocationContext) {\n List subAgents = subAgents();\n if (subAgents == null || subAgents.isEmpty()) {\n return Flowable.empty();\n }\n\n return Flowable.fromIterable(subAgents)\n .concatMap(subAgent -> subAgent.runAsync(invocationContext))\n .repeat(maxIterations.orElse(Integer.MAX_VALUE))\n .takeUntil(LoopAgent::hasEscalateAction);\n }\n\n @Override\n protected Flowable runLiveImpl(InvocationContext invocationContext) {\n return Flowable.error(\n new UnsupportedOperationException(\"runLive is not defined for LoopAgent yet.\"));\n }\n\n private static boolean hasEscalateAction(Event event) {\n return event.actions().escalate().orElse(false);\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/mcp/McpSessionManager.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools.mcp;\n\nimport io.modelcontextprotocol.client.McpClient;\nimport io.modelcontextprotocol.client.McpSyncClient;\nimport io.modelcontextprotocol.spec.McpClientTransport;\nimport io.modelcontextprotocol.spec.McpSchema.ClientCapabilities;\nimport io.modelcontextprotocol.spec.McpSchema.InitializeResult;\nimport java.time.Duration;\nimport java.util.Optional;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * Manages MCP client sessions.\n *\n *

This class provides methods for creating and initializing MCP client sessions, handling\n * different connection parameters and transport builders.\n */\n// TODO(b/413489523): Implement this class.\npublic class McpSessionManager {\n\n private final Object connectionParams; // ServerParameters or SseServerParameters\n private static final Logger logger = LoggerFactory.getLogger(McpSessionManager.class);\n\n public McpSessionManager(Object connectionParams) {\n this.connectionParams = connectionParams;\n }\n\n public McpSyncClient createSession() {\n return initializeSession(this.connectionParams);\n }\n\n public static McpSyncClient initializeSession(Object connectionParams) {\n return initializeSession(connectionParams, new DefaultMcpTransportBuilder());\n }\n\n public static McpSyncClient initializeSession(\n Object connectionParams, McpTransportBuilder transportBuilder) {\n Duration initializationTimeout = null;\n Duration requestTimeout = null;\n McpClientTransport transport = transportBuilder.build(connectionParams);\n if (connectionParams instanceof SseServerParameters sseServerParams) {\n initializationTimeout = sseServerParams.timeout();\n requestTimeout = sseServerParams.sseReadTimeout();\n }\n McpSyncClient client =\n McpClient.sync(transport)\n .initializationTimeout(\n Optional.ofNullable(initializationTimeout).orElse(Duration.ofSeconds(10)))\n .requestTimeout(Optional.ofNullable(requestTimeout).orElse(Duration.ofSeconds(10)))\n .capabilities(ClientCapabilities.builder().build())\n .build();\n InitializeResult initResult = client.initialize();\n logger.debug(\"Initialize Client Result: {}\", initResult);\n return client;\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/agents/InvocationContext.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.agents;\n\nimport com.google.adk.artifacts.BaseArtifactService;\nimport com.google.adk.exceptions.LlmCallsLimitExceededException;\nimport com.google.adk.sessions.BaseSessionService;\nimport com.google.adk.sessions.Session;\nimport com.google.genai.types.Content;\nimport java.util.Objects;\nimport java.util.Optional;\nimport java.util.UUID;\nimport javax.annotation.Nullable;\n\n/** The context for an agent invocation. */\npublic class InvocationContext {\n\n private final BaseSessionService sessionService;\n private final BaseArtifactService artifactService;\n private final Optional liveRequestQueue;\n\n private Optional branch;\n private final String invocationId;\n private BaseAgent agent;\n private final Session session;\n\n private final Optional userContent;\n private final RunConfig runConfig;\n private boolean endInvocation;\n private final InvocationCostManager invocationCostManager = new InvocationCostManager();\n\n private InvocationContext(\n BaseSessionService sessionService,\n BaseArtifactService artifactService,\n Optional liveRequestQueue,\n Optional branch,\n String invocationId,\n BaseAgent agent,\n Session session,\n Optional userContent,\n RunConfig runConfig,\n boolean endInvocation) {\n this.sessionService = sessionService;\n this.artifactService = artifactService;\n this.liveRequestQueue = liveRequestQueue;\n this.branch = branch;\n this.invocationId = invocationId;\n this.agent = agent;\n this.session = session;\n this.userContent = userContent;\n this.runConfig = runConfig;\n this.endInvocation = endInvocation;\n }\n\n public static InvocationContext create(\n BaseSessionService sessionService,\n BaseArtifactService artifactService,\n String invocationId,\n BaseAgent agent,\n Session session,\n Content userContent,\n RunConfig runConfig) {\n return new InvocationContext(\n sessionService,\n artifactService,\n Optional.empty(),\n /* branch= */ Optional.empty(),\n invocationId,\n agent,\n session,\n Optional.ofNullable(userContent),\n runConfig,\n false);\n }\n\n public static InvocationContext create(\n BaseSessionService sessionService,\n BaseArtifactService artifactService,\n BaseAgent agent,\n Session session,\n LiveRequestQueue liveRequestQueue,\n RunConfig runConfig) {\n return new InvocationContext(\n sessionService,\n artifactService,\n Optional.ofNullable(liveRequestQueue),\n /* branch= */ Optional.empty(),\n InvocationContext.newInvocationContextId(),\n agent,\n session,\n Optional.empty(),\n runConfig,\n false);\n }\n\n public static InvocationContext copyOf(InvocationContext other) {\n return new InvocationContext(\n other.sessionService,\n other.artifactService,\n other.liveRequestQueue,\n other.branch,\n other.invocationId,\n other.agent,\n other.session,\n other.userContent,\n other.runConfig,\n other.endInvocation);\n }\n\n public BaseSessionService sessionService() {\n return sessionService;\n }\n\n public BaseArtifactService artifactService() {\n return artifactService;\n }\n\n public Optional liveRequestQueue() {\n return liveRequestQueue;\n }\n\n public String invocationId() {\n return invocationId;\n }\n\n public void branch(@Nullable String branch) {\n this.branch = Optional.ofNullable(branch);\n }\n\n public Optional branch() {\n return branch;\n }\n\n public BaseAgent agent() {\n return agent;\n }\n\n public void agent(BaseAgent agent) {\n this.agent = agent;\n }\n\n public Session session() {\n return session;\n }\n\n public Optional userContent() {\n return userContent;\n }\n\n public RunConfig runConfig() {\n return runConfig;\n }\n\n public boolean endInvocation() {\n return endInvocation;\n }\n\n public void setEndInvocation(boolean endInvocation) {\n this.endInvocation = endInvocation;\n }\n\n public String appName() {\n return session.appName();\n }\n\n public String userId() {\n return session.userId();\n }\n\n public static String newInvocationContextId() {\n return \"e-\" + UUID.randomUUID();\n }\n\n public void incrementLlmCallsCount() throws LlmCallsLimitExceededException {\n this.invocationCostManager.incrementAndEnforceLlmCallsLimit(this.runConfig);\n }\n\n private static class InvocationCostManager {\n private int numberOfLlmCalls = 0;\n\n public void incrementAndEnforceLlmCallsLimit(RunConfig runConfig)\n throws LlmCallsLimitExceededException {\n this.numberOfLlmCalls++;\n\n if (runConfig != null\n && runConfig.maxLlmCalls() > 0\n && this.numberOfLlmCalls > runConfig.maxLlmCalls()) {\n throw new LlmCallsLimitExceededException(\n \"Max number of llm calls limit of \" + runConfig.maxLlmCalls() + \" exceeded\");\n }\n }\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (!(o instanceof InvocationContext that)) {\n return false;\n }\n return endInvocation == that.endInvocation\n && Objects.equals(sessionService, that.sessionService)\n && Objects.equals(artifactService, that.artifactService)\n && Objects.equals(liveRequestQueue, that.liveRequestQueue)\n && Objects.equals(branch, that.branch)\n && Objects.equals(invocationId, that.invocationId)\n && Objects.equals(agent, that.agent)\n && Objects.equals(session, that.session)\n && Objects.equals(userContent, that.userContent)\n && Objects.equals(runConfig, that.runConfig);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(\n sessionService,\n artifactService,\n liveRequestQueue,\n branch,\n invocationId,\n agent,\n session,\n userContent,\n runConfig,\n endInvocation);\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/agents/CallbackContext.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.agents;\n\nimport com.google.adk.events.EventActions;\nimport com.google.adk.sessions.State;\nimport com.google.genai.types.Part;\nimport io.reactivex.rxjava3.core.Maybe;\nimport java.util.Optional;\n\n/** The context of various callbacks for an agent invocation. */\npublic class CallbackContext extends ReadonlyContext {\n\n protected EventActions eventActions;\n private final State state;\n\n /**\n * Initializes callback context.\n *\n * @param invocationContext Current invocation context.\n * @param eventActions Callback event actions.\n */\n public CallbackContext(InvocationContext invocationContext, EventActions eventActions) {\n super(invocationContext);\n this.eventActions = eventActions != null ? eventActions : EventActions.builder().build();\n this.state = new State(invocationContext.session().state(), this.eventActions.stateDelta());\n }\n\n /** Returns the delta-aware state of the current callback. */\n @Override\n public State state() {\n return state;\n }\n\n /** Returns the EventActions associated with this context. */\n public EventActions eventActions() {\n return eventActions;\n }\n\n /**\n * Loads an artifact from the artifact service associated with the current session.\n *\n * @param filename Artifact file name.\n * @param version Artifact version (optional).\n * @return loaded part, or empty if not found.\n * @throws IllegalStateException if the artifact service is not initialized.\n */\n public Maybe loadArtifact(String filename, Optional version) {\n if (invocationContext.artifactService() == null) {\n throw new IllegalStateException(\"Artifact service is not initialized.\");\n }\n return invocationContext\n .artifactService()\n .loadArtifact(\n invocationContext.appName(),\n invocationContext.userId(),\n invocationContext.session().id(),\n filename,\n version);\n }\n\n /**\n * Saves an artifact and records it as a delta for the current session.\n *\n * @param filename Artifact file name.\n * @param artifact Artifact content to save.\n * @throws IllegalStateException if the artifact service is not initialized.\n */\n public void saveArtifact(String filename, Part artifact) {\n if (invocationContext.artifactService() == null) {\n throw new IllegalStateException(\"Artifact service is not initialized.\");\n }\n var unused =\n invocationContext\n .artifactService()\n .saveArtifact(\n invocationContext.appName(),\n invocationContext.userId(),\n invocationContext.session().id(),\n filename,\n artifact);\n this.eventActions.artifactDelta().put(filename, artifact);\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/ToolContext.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools;\n\nimport com.google.adk.agents.CallbackContext;\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.artifacts.ListArtifactsResponse;\nimport com.google.adk.events.EventActions;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.List;\nimport java.util.Optional;\n\n/** ToolContext object provides a structured context for executing tools or functions. */\npublic class ToolContext extends CallbackContext {\n private Optional functionCallId = Optional.empty();\n\n private ToolContext(\n InvocationContext invocationContext,\n EventActions eventActions,\n Optional functionCallId) {\n super(invocationContext, eventActions);\n this.functionCallId = functionCallId;\n }\n\n public EventActions actions() {\n return this.eventActions;\n }\n\n public void setActions(EventActions actions) {\n this.eventActions = actions;\n }\n\n public Optional functionCallId() {\n return functionCallId;\n }\n\n public void functionCallId(String functionCallId) {\n this.functionCallId = Optional.ofNullable(functionCallId);\n }\n\n @SuppressWarnings(\"unused\")\n private void requestCredential() {\n // TODO: b/414678311 - Implement credential request logic. Make this public.\n throw new UnsupportedOperationException(\"Credential request not implemented yet.\");\n }\n\n @SuppressWarnings(\"unused\")\n private void getAuthResponse() {\n // TODO: b/414678311 - Implement auth response retrieval logic. Make this public.\n throw new UnsupportedOperationException(\"Auth response retrieval not implemented yet.\");\n }\n\n @SuppressWarnings(\"unused\")\n private void searchMemory() {\n // TODO: b/414680316 - Implement search memory logic. Make this public.\n throw new UnsupportedOperationException(\"Search memory not implemented yet.\");\n }\n\n /** Lists the filenames of the artifacts attached to the current session. */\n public Single> listArtifacts() {\n if (invocationContext.artifactService() == null) {\n throw new IllegalStateException(\"Artifact service is not initialized.\");\n }\n return invocationContext\n .artifactService()\n .listArtifactKeys(\n invocationContext.session().appName(),\n invocationContext.session().userId(),\n invocationContext.session().id())\n .map(ListArtifactsResponse::filenames);\n }\n\n public static Builder builder(InvocationContext invocationContext) {\n return new Builder(invocationContext);\n }\n\n public Builder toBuilder() {\n return new Builder(invocationContext)\n .actions(eventActions)\n .functionCallId(functionCallId.orElse(null));\n }\n\n /** Builder for {@link ToolContext}. */\n public static final class Builder {\n private final InvocationContext invocationContext;\n private EventActions eventActions = EventActions.builder().build(); // Default empty actions\n private Optional functionCallId = Optional.empty();\n\n private Builder(InvocationContext invocationContext) {\n this.invocationContext = invocationContext;\n }\n\n @CanIgnoreReturnValue\n public Builder actions(EventActions actions) {\n this.eventActions = actions;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder functionCallId(String functionCallId) {\n this.functionCallId = Optional.ofNullable(functionCallId);\n return this;\n }\n\n public ToolContext build() {\n return new ToolContext(invocationContext, eventActions, functionCallId);\n }\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/SchemaUtils.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk;\n\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.google.genai.types.Schema;\nimport com.google.genai.types.Type;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\n/** Utility class for validating schemas. */\npublic final class SchemaUtils {\n\n private SchemaUtils() {} // Private constructor for utility class\n\n /**\n * Matches a value against a schema type.\n *\n * @param value The value to match.\n * @param schema The schema to match against.\n * @param isInput Whether the value is an input or output.\n * @return True if the value matches the schema type, false otherwise.\n * @throws IllegalArgumentException If the schema type is not supported.\n */\n @SuppressWarnings(\"unchecked\") // For tool parameter type casting.\n private static Boolean matchType(Object value, Schema schema, Boolean isInput) {\n // Based on types from https://cloud.google.com/vertex-ai/docs/reference/rest/v1/Schema\n Type.Known type = schema.type().get().knownEnum();\n switch (type) {\n case STRING:\n return value instanceof String;\n case INTEGER:\n return value instanceof Integer;\n case BOOLEAN:\n return value instanceof Boolean;\n case NUMBER:\n return value instanceof Number;\n case ARRAY:\n if (value instanceof List) {\n for (Object element : (List) value) {\n if (!matchType(element, schema.items().get(), isInput)) {\n return false;\n }\n }\n return true;\n }\n return false;\n case OBJECT:\n if (value instanceof Map) {\n validateMapOnSchema((Map) value, schema, isInput);\n return true;\n } else {\n return false;\n }\n case TYPE_UNSPECIFIED:\n throw new IllegalArgumentException(\n \"Unsupported type: \" + type + \" is not a Open API data type.\");\n default:\n // This category includes NULL, which is not supported.\n break;\n }\n return false;\n }\n\n /**\n * Validates a map against a schema.\n *\n * @param args The map to validate.\n * @param schema The schema to validate against.\n * @param isInput Whether the map is an input or output.\n * @throws IllegalArgumentException If the map does not match the schema.\n */\n public static void validateMapOnSchema(Map args, Schema schema, Boolean isInput) {\n Map properties = schema.properties().get();\n for (Entry arg : args.entrySet()) {\n // Check if the argument is in the schema.\n if (!properties.containsKey(arg.getKey())) {\n if (isInput) {\n throw new IllegalArgumentException(\n \"Input arg: \" + arg.getKey() + \" does not match agent input schema: \" + schema);\n } else {\n throw new IllegalArgumentException(\n \"Output arg: \" + arg.getKey() + \" does not match agent output schema: \" + schema);\n }\n }\n // Check if the argument type matches the schema type.\n if (!matchType(arg.getValue(), properties.get(arg.getKey()), isInput)) {\n if (isInput) {\n throw new IllegalArgumentException(\n \"Input arg: \" + arg.getKey() + \" does not match agent input schema: \" + schema);\n } else {\n throw new IllegalArgumentException(\n \"Output arg: \" + arg.getKey() + \" does not match agent output schema: \" + schema);\n }\n }\n }\n // Check if all required arguments are present.\n if (schema.required().isPresent()) {\n for (String required : schema.required().get()) {\n if (!args.containsKey(required)) {\n if (isInput) {\n throw new IllegalArgumentException(\"Input args does not contain required \" + required);\n } else {\n throw new IllegalArgumentException(\"Output args does not contain required \" + required);\n }\n }\n }\n }\n }\n\n /**\n * Validates an output string against a schema.\n *\n * @param output The output string to validate.\n * @param schema The schema to validate against.\n * @return The output map.\n * @throws IllegalArgumentException If the output string does not match the schema.\n * @throws JsonProcessingException If the output string cannot be parsed.\n */\n @SuppressWarnings(\"unchecked\") // For tool parameter type casting.\n public static Map validateOutputSchema(String output, Schema schema)\n throws JsonProcessingException {\n Map outputMap = JsonBaseModel.getMapper().readValue(output, HashMap.class);\n validateMapOnSchema(outputMap, schema, false);\n return outputMap;\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/llmflows/Identity.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows.llmflows;\n\nimport com.google.adk.agents.BaseAgent;\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.models.LlmRequest;\nimport com.google.common.base.Strings;\nimport com.google.common.collect.ImmutableList;\nimport io.reactivex.rxjava3.core.Single;\n\n/** {@link RequestProcessor} that gives the agent identity from the framework */\npublic final class Identity implements RequestProcessor {\n\n public Identity() {}\n\n @Override\n public Single processRequest(\n InvocationContext context, LlmRequest request) {\n BaseAgent agent = context.agent();\n StringBuilder builder =\n new StringBuilder()\n .append(\"You are an agent. Your internal name is \")\n .append(agent.name())\n .append(\".\");\n if (!Strings.isNullOrEmpty(agent.description())) {\n builder.append(\" The description about you is \").append(agent.description());\n }\n return Single.just(\n RequestProcessor.RequestProcessingResult.create(\n request.toBuilder().appendInstructions(ImmutableList.of(builder.toString())).build(),\n ImmutableList.of()));\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/agents/SequentialAgent.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.agents;\n\nimport com.google.adk.events.Event;\nimport com.google.common.collect.ImmutableList;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport io.reactivex.rxjava3.core.Flowable;\nimport java.util.List;\n\n/** An agent that runs its sub-agents sequentially. */\npublic class SequentialAgent extends BaseAgent {\n\n /**\n * Constructor for SequentialAgent.\n *\n * @param name The agent's name.\n * @param description The agent's description.\n * @param subAgents The list of sub-agents to run sequentially.\n * @param beforeAgentCallback Optional callback before the agent runs.\n * @param afterAgentCallback Optional callback after the agent runs.\n */\n private SequentialAgent(\n String name,\n String description,\n List subAgents,\n List beforeAgentCallback,\n List afterAgentCallback) {\n\n super(name, description, subAgents, beforeAgentCallback, afterAgentCallback);\n }\n\n /** Builder for {@link SequentialAgent}. */\n public static class Builder {\n private String name;\n private String description;\n private List subAgents;\n private ImmutableList beforeAgentCallback;\n private ImmutableList afterAgentCallback;\n\n @CanIgnoreReturnValue\n public Builder name(String name) {\n this.name = name;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder description(String description) {\n this.description = description;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder subAgents(List subAgents) {\n this.subAgents = subAgents;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder subAgents(BaseAgent... subAgents) {\n this.subAgents = ImmutableList.copyOf(subAgents);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeAgentCallback(Callbacks.BeforeAgentCallback beforeAgentCallback) {\n this.beforeAgentCallback = ImmutableList.of(beforeAgentCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeAgentCallback(\n List beforeAgentCallback) {\n this.beforeAgentCallback = CallbackUtil.getBeforeAgentCallbacks(beforeAgentCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterAgentCallback(Callbacks.AfterAgentCallback afterAgentCallback) {\n this.afterAgentCallback = ImmutableList.of(afterAgentCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterAgentCallback(List afterAgentCallback) {\n this.afterAgentCallback = CallbackUtil.getAfterAgentCallbacks(afterAgentCallback);\n return this;\n }\n\n public SequentialAgent build() {\n // TODO(b/410859954): Add validation for required fields like name.\n return new SequentialAgent(\n name, description, subAgents, beforeAgentCallback, afterAgentCallback);\n }\n }\n\n public static Builder builder() {\n return new Builder();\n }\n\n /**\n * Runs sub-agents sequentially.\n *\n * @param invocationContext Invocation context.\n * @return Flowable emitting events from sub-agents.\n */\n @Override\n protected Flowable runAsyncImpl(InvocationContext invocationContext) {\n return Flowable.fromIterable(subAgents())\n .concatMap(subAgent -> subAgent.runAsync(invocationContext));\n }\n\n /**\n * Runs sub-agents sequentially in live mode.\n *\n * @param invocationContext Invocation context.\n * @return Flowable emitting events from sub-agents in live mode.\n */\n @Override\n protected Flowable runLiveImpl(InvocationContext invocationContext) {\n return Flowable.fromIterable(subAgents())\n .concatMap(subAgent -> subAgent.runLive(invocationContext));\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/models/BaseLlmConnection.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.models;\n\nimport com.google.genai.types.Blob;\nimport com.google.genai.types.Content;\nimport io.reactivex.rxjava3.core.Completable;\nimport io.reactivex.rxjava3.core.Flowable;\nimport java.util.List;\n\n/** The base class for a live model connection. */\npublic interface BaseLlmConnection {\n\n /**\n * Sends the conversation history to the model.\n *\n *

You call this method right after setting up the model connection. The model will respond if\n * the last content is from user, otherwise it will wait for new user input before responding.\n */\n Completable sendHistory(List history);\n\n /**\n * Sends a user content to the model.\n *\n *

The model will respond immediately upon receiving the content. If you send function\n * responses, all parts in the content should be function responses.\n */\n Completable sendContent(Content content);\n\n /**\n * Sends a chunk of audio or a frame of video to the model in realtime.\n *\n *

The model may not respond immediately upon receiving the blob. It will do voice activity\n * detection and decide when to respond.\n */\n Completable sendRealtime(Blob blob);\n\n /** Receives the model responses. */\n Flowable receive();\n\n /** Closes the connection. */\n void close();\n\n /** Closes the connection with an error. */\n void close(Throwable throwable);\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/agents/CallbackUtil.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.agents;\n\nimport com.google.adk.agents.Callbacks.AfterAgentCallback;\nimport com.google.adk.agents.Callbacks.AfterAgentCallbackBase;\nimport com.google.adk.agents.Callbacks.AfterAgentCallbackSync;\nimport com.google.adk.agents.Callbacks.BeforeAgentCallback;\nimport com.google.adk.agents.Callbacks.BeforeAgentCallbackBase;\nimport com.google.adk.agents.Callbacks.BeforeAgentCallbackSync;\nimport com.google.common.collect.ImmutableList;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport io.reactivex.rxjava3.core.Maybe;\nimport java.util.List;\nimport org.jspecify.annotations.Nullable;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/** Utility methods for normalizing agent callbacks. */\npublic final class CallbackUtil {\n private static final Logger logger = LoggerFactory.getLogger(CallbackUtil.class);\n\n /**\n * Normalizes before-agent callbacks.\n *\n * @param beforeAgentCallback Callback list (sync or async).\n * @return normalized async callbacks, or null if input is null.\n */\n @CanIgnoreReturnValue\n public static @Nullable ImmutableList getBeforeAgentCallbacks(\n List beforeAgentCallback) {\n if (beforeAgentCallback == null) {\n return null;\n } else if (beforeAgentCallback.isEmpty()) {\n return ImmutableList.of();\n } else {\n ImmutableList.Builder builder = ImmutableList.builder();\n for (BeforeAgentCallbackBase callback : beforeAgentCallback) {\n if (callback instanceof BeforeAgentCallback beforeAgentCallbackInstance) {\n builder.add(beforeAgentCallbackInstance);\n } else if (callback instanceof BeforeAgentCallbackSync beforeAgentCallbackSyncInstance) {\n builder.add(\n (BeforeAgentCallback)\n (callbackContext) ->\n Maybe.fromOptional(beforeAgentCallbackSyncInstance.call(callbackContext)));\n } else {\n logger.warn(\n \"Invalid beforeAgentCallback callback type: %s. Ignoring this callback.\",\n callback.getClass().getName());\n }\n }\n return builder.build();\n }\n }\n\n /**\n * Normalizes after-agent callbacks.\n *\n * @param afterAgentCallback Callback list (sync or async).\n * @return normalized async callbacks, or null if input is null.\n */\n @CanIgnoreReturnValue\n public static @Nullable ImmutableList getAfterAgentCallbacks(\n List afterAgentCallback) {\n if (afterAgentCallback == null) {\n return null;\n } else if (afterAgentCallback.isEmpty()) {\n return ImmutableList.of();\n } else {\n ImmutableList.Builder builder = ImmutableList.builder();\n for (AfterAgentCallbackBase callback : afterAgentCallback) {\n if (callback instanceof AfterAgentCallback afterAgentCallbackInstance) {\n builder.add(afterAgentCallbackInstance);\n } else if (callback instanceof AfterAgentCallbackSync afterAgentCallbackSyncInstance) {\n builder.add(\n (AfterAgentCallback)\n (callbackContext) ->\n Maybe.fromOptional(afterAgentCallbackSyncInstance.call(callbackContext)));\n } else {\n logger.warn(\n \"Invalid afterAgentCallback callback type: %s. Ignoring this callback.\",\n callback.getClass().getName());\n }\n }\n return builder.build();\n }\n }\n\n private CallbackUtil() {}\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/llmflows/audio/VertexSpeechClient.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows.llmflows.audio;\n\nimport com.google.cloud.speech.v1.RecognitionAudio;\nimport com.google.cloud.speech.v1.RecognitionConfig;\nimport com.google.cloud.speech.v1.RecognizeResponse;\nimport com.google.cloud.speech.v1.SpeechClient;\nimport java.io.IOException;\n\n/** Implementation of SpeechClientInterface using Vertex AI SpeechClient. */\npublic class VertexSpeechClient implements SpeechClientInterface {\n\n private final SpeechClient speechClient;\n\n /**\n * Constructs a VertexSpeechClient, initializing the underlying Google Cloud SpeechClient.\n *\n * @throws IOException if SpeechClient creation fails.\n */\n public VertexSpeechClient() throws IOException {\n this.speechClient = SpeechClient.create();\n }\n\n /**\n * Performs synchronous speech recognition on the given audio input.\n *\n * @param config Recognition configuration (e.g., language, encoding).\n * @param audio Audio data to recognize.\n * @return The recognition result.\n */\n @Override\n public RecognizeResponse recognize(RecognitionConfig config, RecognitionAudio audio) {\n // The original SpeechClient.recognize doesn't declare checked exceptions other than what might\n // be runtime. The interface declares Exception to be more general for other implementations.\n return speechClient.recognize(config, audio);\n }\n\n @Override\n public void close() throws Exception {\n if (speechClient != null) {\n speechClient.close();\n }\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/network/HttpApiResponse.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.network;\n\nimport com.google.genai.errors.ApiException;\nimport com.google.genai.errors.ClientException;\nimport com.google.genai.errors.ServerException;\nimport java.io.IOException;\nimport okhttp3.Response;\nimport okhttp3.ResponseBody;\n\n/** Wraps a real HTTP response to expose the methods needed by the GenAI SDK. */\npublic final class HttpApiResponse extends ApiResponse {\n\n private final Response response;\n\n /** Constructs a HttpApiResponse instance with the response. */\n public HttpApiResponse(Response response) {\n throwFromResponse(response);\n this.response = response;\n }\n\n /** Returns the ResponseBody from the response. */\n @Override\n public ResponseBody getEntity() {\n return response.body();\n }\n\n /**\n * Throws an ApiException from the response if the response is not a OK status. This method is\n * adapted to work with OkHttp's Response.\n *\n * @param response The response from the API call.\n */\n private void throwFromResponse(Response response) {\n if (response.isSuccessful()) {\n return;\n }\n int code = response.code();\n String status = response.message();\n String message = getErrorMessageFromResponse(response);\n if (code >= 400 && code < 500) { // Client errors.\n throw new ClientException(code, status, message);\n } else if (code >= 500 && code < 600) { // Server errors.\n throw new ServerException(code, status, message);\n } else {\n throw new ApiException(code, status, message);\n }\n }\n\n private String getErrorMessageFromResponse(Response response) {\n try {\n if (response.body() != null) {\n return response.body().string(); // Consume only once.\n }\n } catch (IOException e) {\n // Log the error. Return a generic message to avoid masking original exception.\n return \"Error reading response body\";\n }\n return \"\";\n }\n\n /** Closes the Http response. */\n @Override\n public void close() {\n response.close();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/agents/LiveRequestQueue.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.agents;\n\nimport com.google.genai.types.Blob;\nimport com.google.genai.types.Content;\nimport io.reactivex.rxjava3.core.Flowable;\nimport io.reactivex.rxjava3.processors.FlowableProcessor;\nimport io.reactivex.rxjava3.processors.MulticastProcessor;\n\n/** A queue of live requests to be sent to the model. */\npublic final class LiveRequestQueue {\n private final FlowableProcessor processor;\n\n public LiveRequestQueue() {\n MulticastProcessor processor = MulticastProcessor.create();\n processor.start();\n this.processor = processor.toSerialized();\n }\n\n public void close() {\n processor.onNext(LiveRequest.builder().close(true).build());\n processor.onComplete();\n }\n\n public void content(Content content) {\n processor.onNext(LiveRequest.builder().content(content).build());\n }\n\n public void realtime(Blob blob) {\n processor.onNext(LiveRequest.builder().blob(blob).build());\n }\n\n public void send(LiveRequest request) {\n processor.onNext(request);\n if (request.shouldClose()) {\n processor.onComplete();\n }\n }\n\n public Flowable get() {\n return processor;\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/events/EventActions.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.google.adk.events;\n\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.databind.annotation.JsonDeserialize;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport com.google.genai.types.Part;\nimport java.util.Objects;\nimport java.util.Optional;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentMap;\nimport javax.annotation.Nullable;\n\n/** Represents the actions attached to an event. */\n// TODO - b/414081262 make json wire camelCase\n@JsonDeserialize(builder = EventActions.Builder.class)\npublic class EventActions {\n\n private Optional skipSummarization = Optional.empty();\n private ConcurrentMap stateDelta = new ConcurrentHashMap<>();\n private ConcurrentMap artifactDelta = new ConcurrentHashMap<>();\n private Optional transferToAgent = Optional.empty();\n private Optional escalate = Optional.empty();\n private ConcurrentMap> requestedAuthConfigs =\n new ConcurrentHashMap<>();\n private Optional endInvocation = Optional.empty();\n\n /** Default constructor for Jackson. */\n public EventActions() {}\n\n @JsonProperty(\"skipSummarization\")\n public Optional skipSummarization() {\n return skipSummarization;\n }\n\n public void setSkipSummarization(@Nullable Boolean skipSummarization) {\n this.skipSummarization = Optional.ofNullable(skipSummarization);\n }\n\n public void setSkipSummarization(Optional skipSummarization) {\n this.skipSummarization = skipSummarization;\n }\n\n public void setSkipSummarization(boolean skipSummarization) {\n this.skipSummarization = Optional.of(skipSummarization);\n }\n\n @JsonProperty(\"stateDelta\")\n public ConcurrentMap stateDelta() {\n return stateDelta;\n }\n\n public void setStateDelta(ConcurrentMap stateDelta) {\n this.stateDelta = stateDelta;\n }\n\n @JsonProperty(\"artifactDelta\")\n public ConcurrentMap artifactDelta() {\n return artifactDelta;\n }\n\n public void setArtifactDelta(ConcurrentMap artifactDelta) {\n this.artifactDelta = artifactDelta;\n }\n\n @JsonProperty(\"transferToAgent\")\n public Optional transferToAgent() {\n return transferToAgent;\n }\n\n public void setTransferToAgent(Optional transferToAgent) {\n this.transferToAgent = transferToAgent;\n }\n\n public void setTransferToAgent(String transferToAgent) {\n this.transferToAgent = Optional.ofNullable(transferToAgent);\n }\n\n @JsonProperty(\"escalate\")\n public Optional escalate() {\n return escalate;\n }\n\n public void setEscalate(Optional escalate) {\n this.escalate = escalate;\n }\n\n public void setEscalate(boolean escalate) {\n this.escalate = Optional.of(escalate);\n }\n\n @JsonProperty(\"requestedAuthConfigs\")\n public ConcurrentMap> requestedAuthConfigs() {\n return requestedAuthConfigs;\n }\n\n public void setRequestedAuthConfigs(\n ConcurrentMap> requestedAuthConfigs) {\n this.requestedAuthConfigs = requestedAuthConfigs;\n }\n\n @JsonProperty(\"endInvocation\")\n public Optional endInvocation() {\n return endInvocation;\n }\n\n public void setEndInvocation(Optional endInvocation) {\n this.endInvocation = endInvocation;\n }\n\n public void setEndInvocation(boolean endInvocation) {\n this.endInvocation = Optional.of(endInvocation);\n }\n\n public static Builder builder() {\n return new Builder();\n }\n\n public Builder toBuilder() {\n return new Builder(this);\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (!(o instanceof EventActions that)) {\n return false;\n }\n return Objects.equals(skipSummarization, that.skipSummarization)\n && Objects.equals(stateDelta, that.stateDelta)\n && Objects.equals(artifactDelta, that.artifactDelta)\n && Objects.equals(transferToAgent, that.transferToAgent)\n && Objects.equals(escalate, that.escalate)\n && Objects.equals(requestedAuthConfigs, that.requestedAuthConfigs)\n && Objects.equals(endInvocation, that.endInvocation);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(\n skipSummarization,\n stateDelta,\n artifactDelta,\n transferToAgent,\n escalate,\n requestedAuthConfigs,\n endInvocation);\n }\n\n /** Builder for {@link EventActions}. */\n public static class Builder {\n private Optional skipSummarization = Optional.empty();\n private ConcurrentMap stateDelta = new ConcurrentHashMap<>();\n private ConcurrentMap artifactDelta = new ConcurrentHashMap<>();\n private Optional transferToAgent = Optional.empty();\n private Optional escalate = Optional.empty();\n private ConcurrentMap> requestedAuthConfigs =\n new ConcurrentHashMap<>();\n private Optional endInvocation = Optional.empty();\n\n public Builder() {}\n\n private Builder(EventActions eventActions) {\n this.skipSummarization = eventActions.skipSummarization();\n this.stateDelta = new ConcurrentHashMap<>(eventActions.stateDelta());\n this.artifactDelta = new ConcurrentHashMap<>(eventActions.artifactDelta());\n this.transferToAgent = eventActions.transferToAgent();\n this.escalate = eventActions.escalate();\n this.requestedAuthConfigs = new ConcurrentHashMap<>(eventActions.requestedAuthConfigs());\n this.endInvocation = eventActions.endInvocation();\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"skipSummarization\")\n public Builder skipSummarization(boolean skipSummarization) {\n this.skipSummarization = Optional.of(skipSummarization);\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"stateDelta\")\n public Builder stateDelta(ConcurrentMap value) {\n this.stateDelta = value;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"artifactDelta\")\n public Builder artifactDelta(ConcurrentMap value) {\n this.artifactDelta = value;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"transferToAgent\")\n public Builder transferToAgent(String agentId) {\n this.transferToAgent = Optional.ofNullable(agentId);\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"escalate\")\n public Builder escalate(boolean escalate) {\n this.escalate = Optional.of(escalate);\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"requestedAuthConfigs\")\n public Builder requestedAuthConfigs(\n ConcurrentMap> value) {\n this.requestedAuthConfigs = value;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"endInvocation\")\n public Builder endInvocation(boolean endInvocation) {\n this.endInvocation = Optional.of(endInvocation);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder merge(EventActions other) {\n if (other.skipSummarization().isPresent()) {\n this.skipSummarization = other.skipSummarization();\n }\n if (other.stateDelta() != null) {\n this.stateDelta.putAll(other.stateDelta());\n }\n if (other.artifactDelta() != null) {\n this.artifactDelta.putAll(other.artifactDelta());\n }\n if (other.transferToAgent().isPresent()) {\n this.transferToAgent = other.transferToAgent();\n }\n if (other.escalate().isPresent()) {\n this.escalate = other.escalate();\n }\n if (other.requestedAuthConfigs() != null) {\n this.requestedAuthConfigs.putAll(other.requestedAuthConfigs());\n }\n if (other.endInvocation().isPresent()) {\n this.endInvocation = other.endInvocation();\n }\n return this;\n }\n\n public EventActions build() {\n EventActions eventActions = new EventActions();\n eventActions.setSkipSummarization(this.skipSummarization);\n eventActions.setStateDelta(this.stateDelta);\n eventActions.setArtifactDelta(this.artifactDelta);\n eventActions.setTransferToAgent(this.transferToAgent);\n eventActions.setEscalate(this.escalate);\n eventActions.setRequestedAuthConfigs(this.requestedAuthConfigs);\n eventActions.setEndInvocation(this.endInvocation);\n return eventActions;\n }\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/memory/MemoryEntry.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.memory;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.genai.types.Content;\nimport java.time.Instant;\nimport javax.annotation.Nullable;\n\n/** Represents one memory entry. */\n@AutoValue\npublic abstract class MemoryEntry {\n\n /** Returns the main content of the memory. */\n public abstract Content content();\n\n /** Returns the author of the memory, or null if not set. */\n @Nullable\n public abstract String author();\n\n /**\n * Returns the timestamp when the original content of this memory happened, or null if not set.\n *\n *

This string will be forwarded to LLM. Preferred format is ISO 8601 format\n */\n @Nullable\n public abstract String timestamp();\n\n /** Returns a new builder for creating a {@link MemoryEntry}. */\n public static Builder builder() {\n return new AutoValue_MemoryEntry.Builder();\n }\n\n /**\n * Creates a new builder with a copy of this entry's values.\n *\n * @return a new {@link Builder} instance.\n */\n public abstract Builder toBuilder();\n\n /** Builder for {@link MemoryEntry}. */\n @AutoValue.Builder\n public abstract static class Builder {\n\n /**\n * Sets the main content of the memory.\n *\n *

This is a required field.\n */\n public abstract Builder setContent(Content content);\n\n /** Sets the author of the memory. */\n public abstract Builder setAuthor(@Nullable String author);\n\n /** Sets the timestamp when the original content of this memory happened. */\n public abstract Builder setTimestamp(@Nullable String timestamp);\n\n /**\n * A convenience method to set the timestamp from an {@link Instant} object, formatted as an ISO\n * 8601 string.\n *\n * @param instant The timestamp as an Instant object.\n */\n public Builder setTimestamp(Instant instant) {\n return setTimestamp(instant.toString());\n }\n\n /** Builds the immutable {@link MemoryEntry} object. */\n public abstract MemoryEntry build();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/sessions/Session.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.databind.annotation.JsonDeserialize;\nimport com.google.adk.JsonBaseModel;\nimport com.google.adk.events.Event;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport java.time.Duration;\nimport java.time.Instant;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentMap;\n\n/** A {@link Session} object that encapsulates the {@link State} and {@link Event}s of a session. */\n@JsonDeserialize(builder = Session.Builder.class)\npublic final class Session extends JsonBaseModel {\n private final String id;\n\n private final String appName;\n\n private final String userId;\n\n private final State state;\n\n private final List events;\n\n private Instant lastUpdateTime;\n\n public static Builder builder(String id) {\n return new Builder(id);\n }\n\n /** Builder for {@link Session}. */\n public static final class Builder {\n private String id;\n private String appName;\n private String userId;\n private State state = new State(new ConcurrentHashMap<>());\n private List events = new ArrayList<>();\n private Instant lastUpdateTime = Instant.EPOCH;\n\n public Builder(String id) {\n this.id = id;\n }\n\n @JsonCreator\n private Builder() {}\n\n @CanIgnoreReturnValue\n @JsonProperty(\"id\")\n public Builder id(String id) {\n this.id = id;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder state(State state) {\n this.state = state;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"state\")\n public Builder state(ConcurrentMap state) {\n this.state = new State(state);\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"appName\")\n public Builder appName(String appName) {\n this.appName = appName;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"userId\")\n public Builder userId(String userId) {\n this.userId = userId;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"events\")\n public Builder events(List events) {\n this.events = events;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder lastUpdateTime(Instant lastUpdateTime) {\n this.lastUpdateTime = lastUpdateTime;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"lastUpdateTime\")\n public Builder lastUpdateTimeSeconds(double seconds) {\n long secs = (long) seconds;\n // Convert fractional part to nanoseconds\n long nanos = (long) ((seconds - secs) * Duration.ofSeconds(1).toNanos());\n this.lastUpdateTime = Instant.ofEpochSecond(secs, nanos);\n return this;\n }\n\n public Session build() {\n if (id == null) {\n throw new IllegalStateException(\"Session id is null\");\n }\n return new Session(appName, userId, id, state, events, lastUpdateTime);\n }\n }\n\n @JsonProperty(\"id\")\n public String id() {\n return id;\n }\n\n @JsonProperty(\"state\")\n public ConcurrentMap state() {\n return state;\n }\n\n @JsonProperty(\"events\")\n public List events() {\n return events;\n }\n\n @JsonProperty(\"appName\")\n public String appName() {\n return appName;\n }\n\n @JsonProperty(\"userId\")\n public String userId() {\n return userId;\n }\n\n public void lastUpdateTime(Instant lastUpdateTime) {\n this.lastUpdateTime = lastUpdateTime;\n }\n\n public Instant lastUpdateTime() {\n return lastUpdateTime;\n }\n\n @JsonProperty(\"lastUpdateTime\")\n public double getLastUpdateTimeAsDouble() {\n if (lastUpdateTime == null) {\n return 0.0;\n }\n long seconds = lastUpdateTime.getEpochSecond();\n int nanos = lastUpdateTime.getNano();\n return seconds + nanos / (double) Duration.ofSeconds(1).toNanos();\n }\n\n @Override\n public String toString() {\n return toJson();\n }\n\n public static Session fromJson(String json) {\n return fromJsonString(json, Session.class);\n }\n\n private Session(\n String appName,\n String userId,\n String id,\n State state,\n List events,\n Instant lastUpdateTime) {\n this.id = id;\n this.appName = appName;\n this.userId = userId;\n this.state = state;\n this.events = events;\n this.lastUpdateTime = lastUpdateTime;\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/llmflows/ResponseProcessor.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows.llmflows;\n\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.events.Event;\nimport com.google.adk.models.LlmResponse;\nimport com.google.auto.value.AutoValue;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.Optional;\n\npublic interface ResponseProcessor {\n\n @AutoValue\n public abstract static class ResponseProcessingResult {\n public abstract LlmResponse updatedResponse();\n\n public abstract Iterable events();\n\n public abstract Optional transferToAgent();\n\n public static ResponseProcessingResult create(\n LlmResponse updatedResponse, Iterable events, Optional transferToAgent) {\n return new AutoValue_ResponseProcessor_ResponseProcessingResult(\n updatedResponse, events, transferToAgent);\n }\n }\n\n /**\n * Process the LLM response as part of the post-processing stage.\n *\n * @param context the invocation context.\n * @param response the LLM response to process.\n * @return a list of events generated during processing (if any).\n */\n Single processResponse(InvocationContext context, LlmResponse response);\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/llmflows/RequestProcessor.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows.llmflows;\n\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.events.Event;\nimport com.google.adk.models.LlmRequest;\nimport com.google.auto.value.AutoValue;\nimport io.reactivex.rxjava3.core.Single;\n\npublic interface RequestProcessor {\n\n @AutoValue\n public abstract static class RequestProcessingResult {\n public abstract LlmRequest updatedRequest();\n\n public abstract Iterable events();\n\n public static RequestProcessingResult create(\n LlmRequest updatedRequest, Iterable events) {\n return new AutoValue_RequestProcessor_RequestProcessingResult(updatedRequest, events);\n }\n }\n\n /**\n * Process the LLM request as part of the pre-processing stage.\n *\n * @param context the invocation context.\n * @param request the LLM request to process.\n * @return a list of events generated during processing (if any).\n */\n Single processRequest(InvocationContext context, LlmRequest request);\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/BaseToolset.java", "package com.google.adk.tools;\n\nimport com.google.adk.agents.ReadonlyContext;\nimport io.reactivex.rxjava3.core.Flowable;\nimport java.util.List;\nimport java.util.Optional;\n\n/** Base interface for toolsets. */\npublic interface BaseToolset extends AutoCloseable {\n\n /**\n * Return all tools in the toolset based on the provided context.\n *\n * @param readonlyContext Context used to filter tools available to the agent.\n * @return A Single emitting a list of tools available under the specified context.\n */\n Flowable getTools(ReadonlyContext readonlyContext);\n\n /**\n * Performs cleanup and releases resources held by the toolset.\n *\n *

NOTE: This method is invoked, for example, at the end of an agent server's lifecycle or when\n * the toolset is no longer needed. Implementations should ensure that any open connections,\n * files, or other managed resources are properly released to prevent leaks.\n */\n @Override\n void close() throws Exception;\n\n /**\n * Helper method to be used by implementers that returns true if the given tool is in the provided\n * list of tools of if testing against the given ToolPredicate returns true (otherwise false).\n *\n * @param tool The tool to check.\n * @param toolFilter An Optional containing either a ToolPredicate or a List of tool names.\n * @param readonlyContext The current context.\n * @return true if the tool is selected.\n */\n default boolean isToolSelected(\n BaseTool tool, Optional toolFilter, Optional readonlyContext) {\n if (toolFilter.isEmpty()) {\n return true;\n }\n Object filter = toolFilter.get();\n if (filter instanceof ToolPredicate toolPredicate) {\n return toolPredicate.test(tool, readonlyContext);\n }\n if (filter instanceof List) {\n @SuppressWarnings(\"unchecked\")\n List toolNames = (List) filter;\n return toolNames.contains(tool.name());\n }\n return false;\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/agents/ReadonlyContext.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.agents;\n\nimport com.google.adk.events.Event;\nimport com.google.genai.types.Content;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\n\n/** Provides read-only access to the context of an agent run. */\npublic class ReadonlyContext {\n\n protected final InvocationContext invocationContext;\n private List eventsView;\n private Map stateView;\n\n public ReadonlyContext(InvocationContext invocationContext) {\n this.invocationContext = invocationContext;\n }\n\n /** Returns the user content that initiated this invocation. */\n public Optional userContent() {\n return invocationContext.userContent();\n }\n\n /** Returns the ID of the current invocation. */\n public String invocationId() {\n return invocationContext.invocationId();\n }\n\n /** Returns the branch of the current invocation, if present. */\n public Optional branch() {\n return invocationContext.branch();\n }\n\n /** Returns the name of the agent currently running. */\n public String agentName() {\n return invocationContext.agent().name();\n }\n\n /** Returns the session ID. */\n public String sessionId() {\n return invocationContext.session().id();\n }\n\n /**\n * Returns an unmodifiable view of the events of the session.\n *\n *

Warning: This is a live view, not a snapshot.\n */\n public List events() {\n if (eventsView == null) {\n eventsView = Collections.unmodifiableList(invocationContext.session().events());\n }\n return eventsView;\n }\n\n /**\n * Returns an unmodifiable view of the state of the session.\n *\n *

Warning: This is a live view, not a snapshot.\n */\n public Map state() {\n if (stateView == null) {\n stateView = Collections.unmodifiableMap(invocationContext.session().state());\n }\n return stateView;\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/llmflows/AutoFlow.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows.llmflows;\n\nimport com.google.common.collect.ImmutableList;\nimport java.util.Optional;\n\n/** LLM flow with automatic agent transfer support. */\npublic class AutoFlow extends SingleFlow {\n\n /** Adds {@link AgentTransfer} to base request processors. */\n private static final ImmutableList REQUEST_PROCESSORS =\n ImmutableList.builder()\n .addAll(SingleFlow.REQUEST_PROCESSORS)\n .add(new AgentTransfer())\n .build();\n\n /** No additional response processors. */\n private static final ImmutableList RESPONSE_PROCESSORS = ImmutableList.of();\n\n public AutoFlow() {\n this(/* maxSteps= */ Optional.empty());\n }\n\n public AutoFlow(Optional maxSteps) {\n super(REQUEST_PROCESSORS, RESPONSE_PROCESSORS, maxSteps);\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/models/VertexCredentials.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.models;\n\nimport com.google.auth.oauth2.GoogleCredentials;\nimport com.google.auto.value.AutoValue;\nimport java.util.Optional;\nimport javax.annotation.Nullable;\n\n/** Credentials for accessing Gemini models through Vertex. */\n@AutoValue\npublic abstract class VertexCredentials {\n\n public abstract Optional project();\n\n public abstract Optional location();\n\n public abstract Optional credentials();\n\n public static Builder builder() {\n return new AutoValue_VertexCredentials.Builder();\n }\n\n /** Builder for {@link VertexCredentials}. */\n @AutoValue.Builder\n public abstract static class Builder {\n public abstract Builder setProject(Optional value);\n\n public abstract Builder setProject(@Nullable String value);\n\n public abstract Builder setLocation(Optional value);\n\n public abstract Builder setLocation(@Nullable String value);\n\n public abstract Builder setCredentials(Optional value);\n\n public abstract Builder setCredentials(@Nullable GoogleCredentials value);\n\n public abstract VertexCredentials build();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/retrieval/BaseRetrievalTool.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools.retrieval;\n\nimport com.google.adk.tools.BaseTool;\nimport com.google.genai.types.FunctionDeclaration;\nimport com.google.genai.types.Schema;\nimport java.util.Collections;\nimport java.util.Optional;\n\n/** Base class for retrieval tools. */\npublic abstract class BaseRetrievalTool extends BaseTool {\n public BaseRetrievalTool(String name, String description) {\n super(name, description);\n }\n\n public BaseRetrievalTool(String name, String description, boolean isLongRunning) {\n super(name, description, isLongRunning);\n }\n\n @Override\n public Optional declaration() {\n Schema querySchema =\n Schema.builder().type(\"STRING\").description(\"The query to retrieve.\").build();\n Schema parametersSchema =\n Schema.builder()\n .type(\"OBJECT\")\n .properties(Collections.singletonMap(\"query\", querySchema))\n .build();\n\n return Optional.of(\n FunctionDeclaration.builder()\n .name(this.name())\n .description(this.description())\n .parameters(parametersSchema)\n .build());\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/llmflows/audio/SpeechClientInterface.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows.llmflows.audio;\n\nimport com.google.cloud.speech.v1.RecognitionAudio;\nimport com.google.cloud.speech.v1.RecognitionConfig;\nimport com.google.cloud.speech.v1.RecognizeResponse;\n\n/**\n * Interface for a speech-to-text client. Allows for different implementations (e.g., Cloud, Mocks).\n */\npublic interface SpeechClientInterface extends AutoCloseable {\n\n /**\n * Performs synchronous speech recognition.\n *\n * @param config The recognition configuration.\n * @param audio The audio data to transcribe.\n * @return The recognition response.\n * @throws Exception if an error occurs during recognition.\n */\n RecognizeResponse recognize(RecognitionConfig config, RecognitionAudio audio) throws Exception;\n\n /**\n * Closes the client and releases any resources.\n *\n * @throws Exception if an error occurs during closing.\n */\n @Override\n void close() throws Exception;\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/llmflows/SingleFlow.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows.llmflows;\n\nimport com.google.common.collect.ImmutableList;\nimport java.util.List;\nimport java.util.Optional;\n\n/** Basic LLM flow with fixed request processors and no response post-processing. */\npublic class SingleFlow extends BaseLlmFlow {\n\n protected static final ImmutableList REQUEST_PROCESSORS =\n ImmutableList.of(\n new Basic(), new Instructions(), new Identity(), new Contents(), new Examples());\n\n protected static final ImmutableList RESPONSE_PROCESSORS = ImmutableList.of();\n\n public SingleFlow() {\n this(/* maxSteps= */ Optional.empty());\n }\n\n public SingleFlow(Optional maxSteps) {\n this(REQUEST_PROCESSORS, RESPONSE_PROCESSORS, maxSteps);\n }\n\n protected SingleFlow(\n List requestProcessors,\n List responseProcessors,\n Optional maxSteps) {\n super(requestProcessors, responseProcessors, maxSteps);\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/artifacts/BaseArtifactService.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.artifacts;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.genai.types.Part;\nimport io.reactivex.rxjava3.core.Completable;\nimport io.reactivex.rxjava3.core.Maybe;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.Optional;\n\n/** Base interface for artifact services. */\npublic interface BaseArtifactService {\n\n /**\n * Saves an artifact.\n *\n * @param appName the app name\n * @param userId the user ID\n * @param sessionId the session ID\n * @param filename the filename\n * @param artifact the artifact\n * @return the revision ID (version) of the saved artifact.\n */\n Single saveArtifact(\n String appName, String userId, String sessionId, String filename, Part artifact);\n\n /**\n * Gets an artifact.\n *\n * @param appName the app name\n * @param userId the user ID\n * @param sessionId the session ID\n * @param filename the filename\n * @param version Optional version number. If null, loads the latest version.\n * @return the artifact or empty if not found\n */\n Maybe loadArtifact(\n String appName, String userId, String sessionId, String filename, Optional version);\n\n /**\n * Lists all the artifact filenames within a session.\n *\n * @param appName the app name\n * @param userId the user ID\n * @param sessionId the session ID\n * @return the list artifact response containing filenames\n */\n Single listArtifactKeys(String appName, String userId, String sessionId);\n\n /**\n * Deletes an artifact.\n *\n * @param appName the app name\n * @param userId the user ID\n * @param sessionId the session ID\n * @param filename the filename\n */\n Completable deleteArtifact(String appName, String userId, String sessionId, String filename);\n\n /**\n * Lists all the versions (as revision IDs) of an artifact.\n *\n * @param appName the app name\n * @param userId the user ID\n * @param sessionId the session ID\n * @param filename the artifact filename\n * @return A list of integer version numbers.\n */\n Single> listVersions(\n String appName, String userId, String sessionId, String filename);\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/sessions/ListSessionsResponse.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\nimport static com.google.common.collect.ImmutableList.toImmutableList;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\nimport java.util.List;\n\n/** Response for listing sessions. */\n@AutoValue\npublic abstract class ListSessionsResponse {\n\n public abstract ImmutableList sessions();\n\n public List sessionIds() {\n return sessions().stream().map(Session::id).collect(toImmutableList());\n }\n\n /** Builder for {@link ListSessionsResponse}. */\n @AutoValue.Builder\n public abstract static class Builder {\n\n public abstract Builder sessions(List sessions);\n\n public abstract ListSessionsResponse build();\n }\n\n public static Builder builder() {\n return new AutoValue_ListSessionsResponse.Builder().sessions(ImmutableList.of());\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/models/Model.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.models;\n\nimport com.google.auto.value.AutoValue;\nimport java.util.Optional;\n\n/** Represents a model by name or instance. */\n@AutoValue\npublic abstract class Model {\n\n public abstract Optional modelName();\n\n public abstract Optional model();\n\n public static Builder builder() {\n return new AutoValue_Model.Builder();\n }\n\n public abstract Builder toBuilder();\n\n /** Builder for {@link Model}. */\n @AutoValue.Builder\n public abstract static class Builder {\n\n public abstract Builder modelName(String modelName);\n\n public abstract Builder model(BaseLlm model);\n\n public abstract Model build();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/memory/SearchMemoryResponse.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.memory;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\nimport java.util.List;\n\n/** Represents the response from a memory search. */\n@AutoValue\npublic abstract class SearchMemoryResponse {\n\n /** Returns a list of memory entries that relate to the search query. */\n public abstract ImmutableList memories();\n\n /** Creates a new builder for {@link SearchMemoryResponse}. */\n public static Builder builder() {\n return new AutoValue_SearchMemoryResponse.Builder().setMemories(ImmutableList.of());\n }\n\n /** Builder for {@link SearchMemoryResponse}. */\n @AutoValue.Builder\n public abstract static class Builder {\n\n abstract Builder setMemories(ImmutableList memories);\n\n /** Sets the list of memory entries using a list. */\n public Builder setMemories(List memories) {\n return setMemories(ImmutableList.copyOf(memories));\n }\n\n /** Builds the immutable {@link SearchMemoryResponse} object. */\n public abstract SearchMemoryResponse build();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/mcp/SseServerParameters.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools.mcp;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableMap;\nimport java.time.Duration;\nimport java.util.Map;\nimport javax.annotation.Nullable;\n\n/** Parameters for establishing a MCP Server-Sent Events (SSE) connection. */\n@AutoValue\npublic abstract class SseServerParameters {\n\n /** The URL of the SSE server. */\n public abstract String url();\n\n /** Optional headers to include in the SSE connection request. */\n @Nullable\n public abstract ImmutableMap headers();\n\n /** The timeout for the initial connection attempt. */\n public abstract Duration timeout();\n\n /** The timeout for reading data from the SSE stream. */\n public abstract Duration sseReadTimeout();\n\n /** Creates a new builder for {@link SseServerParameters}. */\n public static Builder builder() {\n return new AutoValue_SseServerParameters.Builder()\n .timeout(Duration.ofSeconds(5))\n .sseReadTimeout(Duration.ofMinutes(5));\n }\n\n /** Builder for {@link SseServerParameters}. */\n @AutoValue.Builder\n public abstract static class Builder {\n /** Sets the URL of the SSE server. */\n public abstract Builder url(String url);\n\n /** Sets the headers for the SSE connection request. */\n public abstract Builder headers(@Nullable Map headers);\n\n /** Sets the timeout for the initial connection attempt. */\n public abstract Builder timeout(Duration timeout);\n\n /** Sets the timeout for reading data from the SSE stream. */\n public abstract Builder sseReadTimeout(Duration sseReadTimeout);\n\n /** Builds a new {@link SseServerParameters} instance. */\n public abstract SseServerParameters build();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/utils/Pairs.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.utils;\n\nimport com.google.common.collect.ImmutableMap;\nimport java.util.concurrent.ConcurrentHashMap;\n\n/** Utility class for creating ConcurrentHashMaps. */\npublic final class Pairs {\n\n private Pairs() {}\n\n /**\n * Returns a new, empty {@code ConcurrentHashMap}.\n *\n * @param the {@code ConcurrentHashMap}'s key type\n * @param the {@code ConcurrentHashMap}'s value type\n * @return an empty {@code ConcurrentHashMap}\n */\n public static ConcurrentHashMap of() {\n return new ConcurrentHashMap<>();\n }\n\n /**\n * Returns a new {@code ConcurrentHashMap} containing a single mapping.\n *\n * @param the {@code ConcurrentHashMap}'s key type\n * @param the {@code ConcurrentHashMap}'s value type\n * @param k1 the mapping's key\n * @param v1 the mapping's value\n * @return a {@code ConcurrentHashMap} containing the specified mapping\n * @throws NullPointerException if the key or the value is {@code null}\n */\n public static ConcurrentHashMap of(K k1, V v1) {\n return new ConcurrentHashMap<>(ImmutableMap.of(k1, v1));\n }\n\n /**\n * Returns a new {@code ConcurrentHashMap} containing two mappings. This method leverages {@code\n * java.util.Map.of} for initial validation.\n *\n * @param the {@code ConcurrentHashMap}'s key type\n * @param the {@code ConcurrentHashMap}'s value type\n * @param k1 the first mapping's key\n * @param v1 the first mapping's value\n * @param k2 the second mapping's key\n * @param v2 the second mapping's value\n * @return a {@code ConcurrentHashMap} containing the specified mappings\n */\n public static ConcurrentHashMap of(K k1, V v1, K k2, V v2) {\n return new ConcurrentHashMap<>(ImmutableMap.of(k1, v1, k2, v2));\n }\n\n /**\n * Returns a new {@code ConcurrentHashMap} containing three mappings. This method leverages {@code\n * java.util.Map.of} for initial validation.\n *\n * @param the {@code ConcurrentHashMap}'s key type\n * @param the {@code ConcurrentHashMap}'s value type\n * @param k1 the first mapping's key\n * @param v1 the first mapping's value\n * @param k2 the second mapping's key\n * @param v2 the second mapping's value\n * @param k3 the third mapping's key\n * @param v3 the third mapping's value\n * @return a {@code ConcurrentHashMap} containing the specified mappings\n */\n public static ConcurrentHashMap of(K k1, V v1, K k2, V v2, K k3, V v3) {\n return new ConcurrentHashMap<>(ImmutableMap.of(k1, v1, k2, v2, k3, v3));\n }\n\n /**\n * Returns a new {@code ConcurrentHashMap} containing four mappings. This method leverages {@code\n * java.util.Map.of} for initial validation.\n *\n * @param the {@code ConcurrentHashMap}'s key type\n * @param the {@code ConcurrentHashMap}'s value type\n * @param k1 the first mapping's key\n * @param v1 the first mapping's value\n * @param k2 the second mapping's key\n * @param v2 the second mapping's value\n * @param k3 the third mapping's key\n * @param v3 the third mapping's value\n * @param k4 the fourth mapping's key\n * @param v4 the fourth mapping's value\n * @return a {@code ConcurrentHashMap} containing the specified mappings\n */\n public static ConcurrentHashMap of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {\n return new ConcurrentHashMap<>(ImmutableMap.of(k1, v1, k2, v2, k3, v3, k4, v4));\n }\n\n /**\n * Returns a new {@code ConcurrentHashMap} containing five mappings. This method leverages {@code\n * java.util.Map.of} for initial validation.\n *\n * @param the {@code ConcurrentHashMap}'s key type\n * @param the {@code ConcurrentHashMap}'s value type\n * @param k1 the first mapping's key\n * @param v1 the first mapping's value\n * @param k2 the second mapping's key\n * @param v2 the second mapping's value\n * @param k3 the third mapping's key\n * @param v3 the third mapping's value\n * @param k4 the fourth mapping's key\n * @param v4 the fourth mapping's value\n * @param k5 the fifth mapping's key\n * @param v5 the fifth mapping's value\n * @return a {@code ConcurrentHashMap} containing the specified mappings\n */\n public static ConcurrentHashMap of(\n K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {\n return new ConcurrentHashMap<>(ImmutableMap.of(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5));\n }\n\n /**\n * Returns a new {@code ConcurrentHashMap} containing six mappings. This method leverages {@code\n * java.util.Map.of} for initial validation.\n *\n * @param the {@code ConcurrentHashMap}'s key type\n * @param the {@code ConcurrentHashMap}'s value type\n * @param k1 the first mapping's key\n * @param v1 the first mapping's value\n * @param k2 the second mapping's key\n * @param v2 the second mapping's value\n * @param k3 the third mapping's key\n * @param v3 the third mapping's value\n * @param k4 the fourth mapping's key\n * @param v4 the fourth mapping's value\n * @param k5 the fifth mapping's key\n * @param v5 the fifth mapping's value\n * @param k6 the sixth mapping's key\n * @param v6 the sixth mapping's value\n * @return a {@code ConcurrentHashMap} containing the specified mappings\n * @throws IllegalArgumentException if there are any duplicate keys (behavior inherited from\n * Map.of)\n * @throws NullPointerException if any key or value is {@code null} (behavior inherited from\n * Map.of)\n */\n public static ConcurrentHashMap of(\n K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6) {\n return new ConcurrentHashMap<>(ImmutableMap.of(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6));\n }\n\n /**\n * Returns a new {@code ConcurrentHashMap} containing seven mappings. This method leverages {@code\n * java.util.Map.of} for initial validation.\n *\n * @param the {@code ConcurrentHashMap}'s key type\n * @param the {@code ConcurrentHashMap}'s value type\n * @param k1 the first mapping's key\n * @param v1 the first mapping's value\n * @param k2 the second mapping's key\n * @param v2 the second mapping's value\n * @param k3 the third mapping's key\n * @param v3 the third mapping's value\n * @param k4 the fourth mapping's key\n * @param v4 the fourth mapping's value\n * @param k5 the fifth mapping's key\n * @param v5 the fifth mapping's value\n * @param k6 the sixth mapping's key\n * @param v6 the sixth mapping's value\n * @param k7 the seventh mapping's key\n * @param v7 the seventh mapping's value\n * @return a {@code ConcurrentHashMap} containing the specified mappings\n */\n public static ConcurrentHashMap of(\n K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7) {\n return new ConcurrentHashMap<>(\n ImmutableMap.of(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6, k7, v7));\n }\n\n /**\n * Returns a new {@code ConcurrentHashMap} containing eight mappings. This method leverages {@code\n * java.util.Map.of} for initial validation.\n *\n * @param the {@code ConcurrentHashMap}'s key type\n * @param the {@code ConcurrentHashMap}'s value type\n * @param k1 the first mapping's key\n * @param v1 the first mapping's value\n * @param k2 the second mapping's key\n * @param v2 the second mapping's value\n * @param k3 the third mapping's key\n * @param v3 the third mapping's value\n * @param k4 the fourth mapping's key\n * @param v4 the fourth mapping's value\n * @param k5 the fifth mapping's key\n * @param v5 the fifth mapping's value\n * @param k6 the sixth mapping's key\n * @param v6 the sixth mapping's value\n * @param k7 the seventh mapping's key\n * @param v7 the seventh mapping's value\n * @param k8 the eighth mapping's key\n * @param v8 the eighth mapping's value\n * @return a {@code ConcurrentHashMap} containing the specified mappings\n */\n public static ConcurrentHashMap of(\n K k1,\n V v1,\n K k2,\n V v2,\n K k3,\n V v3,\n K k4,\n V v4,\n K k5,\n V v5,\n K k6,\n V v6,\n K k7,\n V v7,\n K k8,\n V v8) {\n return new ConcurrentHashMap<>(\n ImmutableMap.of(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6, k7, v7, k8, v8));\n }\n\n /**\n * Returns a new {@code ConcurrentHashMap} containing nine mappings. This method leverages {@code\n * java.util.Map.of} for initial validation.\n *\n * @param the {@code ConcurrentHashMap}'s key type\n * @param the {@code ConcurrentHashMap}'s value type\n * @param k1 the first mapping's key\n * @param v1 the first mapping's value\n * @param k2 the second mapping's key\n * @param v2 the second mapping's value\n * @param k3 the third mapping's key\n * @param v3 the third mapping's value\n * @param k4 the fourth mapping's key\n * @param v4 the fourth mapping's value\n * @param k5 the fifth mapping's key\n * @param v5 the fifth mapping's value\n * @param k6 the sixth mapping's key\n * @param v6 the sixth mapping's value\n * @param k7 the seventh mapping's key\n * @param v7 the seventh mapping's value\n * @param k8 the eighth mapping's key\n * @param v8 the eighth mapping's value\n * @param k9 the ninth mapping's key\n * @param v9 the ninth mapping's value\n * @return a {@code ConcurrentHashMap} containing the specified mappings\n */\n public static ConcurrentHashMap of(\n K k1,\n V v1,\n K k2,\n V v2,\n K k3,\n V v3,\n K k4,\n V v4,\n K k5,\n V v5,\n K k6,\n V v6,\n K k7,\n V v7,\n K k8,\n V v8,\n K k9,\n V v9) {\n return new ConcurrentHashMap<>(\n ImmutableMap.of(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6, k7, v7, k8, v8, k9, v9));\n }\n\n /**\n * Returns a new {@code ConcurrentHashMap} containing ten mappings. This method leverages {@code\n * java.util.Map.of} for initial validation.\n *\n * @param the {@code ConcurrentHashMap}'s key type\n * @param the {@code ConcurrentHashMap}'s value type\n * @param k1 the first mapping's key\n * @param v1 the first mapping's value\n * @param k2 the second mapping's key\n * @param v2 the second mapping's value\n * @param k3 the third mapping's key\n * @param v3 the third mapping's value\n * @param k4 the fourth mapping's key\n * @param v4 the fourth mapping's value\n * @param k5 the fifth mapping's key\n * @param v5 the fifth mapping's value\n * @param k6 the sixth mapping's key\n * @param v6 the sixth mapping's value\n * @param k7 the seventh mapping's key\n * @param v7 the seventh mapping's value\n * @param k8 the eighth mapping's key\n * @param v8 the eighth mapping's value\n * @param k9 the ninth mapping's key\n * @param v9 the ninth mapping's value\n * @param k10 the tenth mapping's key\n * @param v10 the tenth mapping's value\n * @return a {@code ConcurrentHashMap} containing the specified mappings\n */\n public static ConcurrentHashMap of(\n K k1,\n V v1,\n K k2,\n V v2,\n K k3,\n V v3,\n K k4,\n V v4,\n K k5,\n V v5,\n K k6,\n V v6,\n K k7,\n V v7,\n K k8,\n V v8,\n K k9,\n V v9,\n K k10,\n V v10) {\n return new ConcurrentHashMap<>(\n ImmutableMap.of(\n k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6, k7, v7, k8, v8, k9, v9, k10, v10));\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/sessions/State.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\nimport java.util.Collection;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.Objects;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentMap;\n\n/** A {@link State} object that also keeps track of the changes to the state. */\n@SuppressWarnings(\"ShouldNotSubclass\")\npublic final class State implements ConcurrentMap {\n\n public static final String APP_PREFIX = \"app:\";\n public static final String USER_PREFIX = \"user:\";\n public static final String TEMP_PREFIX = \"temp:\";\n\n // Sentinel object to mark removed entries in the delta map\n private static final Object REMOVED = new Object();\n\n private final ConcurrentMap state;\n private final ConcurrentMap delta;\n\n public State(ConcurrentMap state) {\n this(state, new ConcurrentHashMap<>());\n }\n\n public State(ConcurrentMap state, ConcurrentMap delta) {\n this.state = Objects.requireNonNull(state);\n this.delta = delta;\n }\n\n @Override\n public void clear() {\n state.clear();\n }\n\n @Override\n public boolean containsKey(Object key) {\n return state.containsKey(key);\n }\n\n @Override\n public boolean containsValue(Object value) {\n return state.containsValue(value);\n }\n\n @Override\n public Set> entrySet() {\n return state.entrySet();\n }\n\n @Override\n public boolean equals(Object o) {\n if (o == this) {\n return true;\n }\n if (!(o instanceof State other)) {\n return false;\n }\n return state.equals(other.state);\n }\n\n @Override\n public Object get(Object key) {\n return state.get(key);\n }\n\n @Override\n public int hashCode() {\n return state.hashCode();\n }\n\n @Override\n public boolean isEmpty() {\n return state.isEmpty();\n }\n\n @Override\n public Set keySet() {\n return state.keySet();\n }\n\n @Override\n public Object put(String key, Object value) {\n Object oldValue = state.put(key, value);\n delta.put(key, value);\n return oldValue;\n }\n\n @Override\n public Object putIfAbsent(String key, Object value) {\n Object existingValue = state.putIfAbsent(key, value);\n if (existingValue == null) {\n delta.put(key, value);\n }\n return existingValue;\n }\n\n @Override\n public void putAll(Map m) {\n state.putAll(m);\n delta.putAll(m);\n }\n\n @Override\n public Object remove(Object key) {\n if (state.containsKey(key)) {\n delta.put((String) key, REMOVED);\n }\n return state.remove(key);\n }\n\n @Override\n public boolean remove(Object key, Object value) {\n boolean removed = state.remove(key, value);\n if (removed) {\n delta.put((String) key, REMOVED);\n }\n return removed;\n }\n\n @Override\n public boolean replace(String key, Object oldValue, Object newValue) {\n boolean replaced = state.replace(key, oldValue, newValue);\n if (replaced) {\n delta.put(key, newValue);\n }\n return replaced;\n }\n\n @Override\n public Object replace(String key, Object value) {\n Object oldValue = state.replace(key, value);\n if (oldValue != null) {\n delta.put(key, value);\n }\n return oldValue;\n }\n\n @Override\n public int size() {\n return state.size();\n }\n\n @Override\n public Collection values() {\n return state.values();\n }\n\n public boolean hasDelta() {\n return !delta.isEmpty();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/JsonBaseModel.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk;\n\nimport com.fasterxml.jackson.annotation.JsonInclude;\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.fasterxml.jackson.databind.DeserializationFeature;\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.fasterxml.jackson.databind.PropertyNamingStrategies;\nimport com.fasterxml.jackson.datatype.jdk8.Jdk8Module;\nimport com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;\n\n/** The base class for the types that needs JSON serialization/deserialization capability. */\npublic abstract class JsonBaseModel {\n\n private static final ObjectMapper objectMapper = new ObjectMapper();\n\n static {\n objectMapper\n .setSerializationInclusion(JsonInclude.Include.NON_ABSENT)\n .setPropertyNamingStrategy(PropertyNamingStrategies.LOWER_CAMEL_CASE)\n .registerModule(new Jdk8Module())\n .registerModule(new JavaTimeModule()) // TODO: echo sec module replace, locale\n .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);\n }\n\n /** Serializes an object to a Json string. */\n protected static String toJsonString(Object object) {\n try {\n return objectMapper.writeValueAsString(object);\n } catch (JsonProcessingException e) {\n throw new IllegalStateException(e);\n }\n }\n\n public static ObjectMapper getMapper() {\n return JsonBaseModel.objectMapper;\n }\n\n public String toJson() {\n return toJsonString(this);\n }\n\n /** Serializes an object to a JsonNode. */\n protected static JsonNode toJsonNode(Object object) {\n return objectMapper.valueToTree(object);\n }\n\n /** Deserializes a Json string to an object of the given type. */\n public static T fromJsonString(String jsonString, Class clazz) {\n try {\n return objectMapper.readValue(jsonString, clazz);\n } catch (JsonProcessingException e) {\n throw new IllegalStateException(e);\n }\n }\n\n /** Deserializes a JsonNode to an object of the given type. */\n public static T fromJsonNode(JsonNode jsonNode, Class clazz) {\n try {\n return objectMapper.treeToValue(jsonNode, clazz);\n } catch (JsonProcessingException e) {\n throw new IllegalStateException(e);\n }\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/events/EventStream.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.events;\n\nimport java.util.Iterator;\nimport java.util.NoSuchElementException;\nimport java.util.function.Supplier;\n\n/** Iterable stream of {@link Event} objects. */\npublic class EventStream implements Iterable {\n\n private final Supplier eventSupplier;\n\n /** Constructs a new event stream. */\n public EventStream(Supplier eventSupplier) {\n this.eventSupplier = eventSupplier;\n }\n\n /** Returns an iterator that fetches events lazily. */\n @Override\n public Iterator iterator() {\n return new EventIterator();\n }\n\n /** Iterator that returns events from the supplier until it returns {@code null}. */\n private class EventIterator implements Iterator {\n private Event nextEvent = null;\n private boolean finished = false;\n\n /** Returns {@code true} if another event is available. */\n @Override\n public boolean hasNext() {\n if (finished) {\n return false;\n }\n if (nextEvent == null) {\n nextEvent = eventSupplier.get();\n finished = (nextEvent == null);\n }\n return !finished;\n }\n\n /**\n * Returns the next event.\n *\n * @throws NoSuchElementException if no more events are available.\n */\n @Override\n public Event next() {\n if (!hasNext()) {\n throw new NoSuchElementException(\"No more events.\");\n }\n Event currentEvent = nextEvent;\n nextEvent = null;\n return currentEvent;\n }\n }\n}\n"], ["/adk-java/dev/src/main/java/com/google/adk/web/config/AdkWebCorsConfig.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.web.config;\n\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.web.cors.CorsConfiguration;\nimport org.springframework.web.cors.CorsConfigurationSource;\nimport org.springframework.web.cors.UrlBasedCorsConfigurationSource;\nimport org.springframework.web.filter.CorsFilter;\n\n/**\n * Configuration class for setting up Cross-Origin Resource Sharing (CORS) in the ADK Web\n * application. This class defines beans for configuring CORS settings based on properties defined\n * in {@link AdkWebCorsProperties}.\n *\n *

CORS allows the application to handle requests from different origins, enabling secure\n * communication between the frontend and backend services.\n *\n *

Beans provided:\n *\n *

    \n *
  • {@link CorsConfigurationSource}: Configures CORS settings such as allowed origins, methods,\n * headers, credentials, and max age.\n *
  • {@link CorsFilter}: Applies the CORS configuration to incoming requests.\n *
\n */\n@Configuration\npublic class AdkWebCorsConfig {\n\n @Bean\n public CorsConfigurationSource corsConfigurationSource(AdkWebCorsProperties corsProperties) {\n CorsConfiguration configuration = new CorsConfiguration();\n\n configuration.setAllowedOrigins(corsProperties.origins());\n configuration.setAllowedMethods(corsProperties.methods());\n configuration.setAllowedHeaders(corsProperties.headers());\n configuration.setAllowCredentials(corsProperties.allowCredentials());\n configuration.setMaxAge(corsProperties.maxAge());\n\n UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();\n source.registerCorsConfiguration(corsProperties.mapping(), configuration);\n\n return source;\n }\n\n @Bean\n public CorsFilter corsFilter(CorsConfigurationSource corsConfigurationSource) {\n return new CorsFilter(corsConfigurationSource);\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/memory/BaseMemoryService.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.memory;\n\nimport com.google.adk.sessions.Session;\nimport io.reactivex.rxjava3.core.Completable;\nimport io.reactivex.rxjava3.core.Single;\n\n/**\n * Base contract for memory services.\n *\n *

The service provides functionalities to ingest sessions into memory so that the memory can be\n * used for user queries.\n */\npublic interface BaseMemoryService {\n\n /**\n * Adds a session to the memory service.\n *\n *

A session may be added multiple times during its lifetime.\n *\n * @param session The session to add.\n */\n Completable addSessionToMemory(Session session);\n\n /**\n * Searches for sessions that match the query asynchronously.\n *\n * @param appName The name of the application.\n * @param userId The id of the user.\n * @param query The query to search for.\n * @return A {@link SearchMemoryResponse} containing the matching memories.\n */\n Single searchMemory(String appName, String userId, String query);\n}\n"], ["/adk-java/dev/src/main/java/com/google/adk/web/config/AdkWebCorsProperties.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.web.config;\n\nimport java.util.List;\nimport org.springframework.boot.context.properties.ConfigurationProperties;\n\n/**\n * Properties for configuring CORS in ADK Web. This class is used to load CORS settings from\n * application properties.\n */\n@ConfigurationProperties(prefix = \"adk.web.cors\")\npublic record AdkWebCorsProperties(\n String mapping,\n List origins,\n List methods,\n List headers,\n boolean allowCredentials,\n long maxAge) {\n\n public AdkWebCorsProperties {\n mapping = mapping != null ? mapping : \"/**\";\n origins = origins != null && !origins.isEmpty() ? origins : List.of();\n methods =\n methods != null && !methods.isEmpty()\n ? methods\n : List.of(\"GET\", \"POST\", \"PUT\", \"DELETE\", \"OPTIONS\");\n headers = headers != null && !headers.isEmpty() ? headers : List.of(\"*\");\n maxAge = maxAge > 0 ? maxAge : 3600;\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/artifacts/ListArtifactVersionsResponse.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.artifacts;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\nimport com.google.genai.types.Part;\nimport java.util.List;\n\n/** Response for listing artifact versions. */\n@AutoValue\npublic abstract class ListArtifactVersionsResponse {\n\n public abstract ImmutableList versions();\n\n /** Builder for {@link ListArtifactVersionsResponse}. */\n @AutoValue.Builder\n public abstract static class Builder {\n public abstract Builder versions(List versions);\n\n public abstract ListArtifactVersionsResponse build();\n }\n\n public static Builder builder() {\n return new AutoValue_ListArtifactVersionsResponse.Builder();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/mcp/McpTransportBuilder.java", "package com.google.adk.tools.mcp;\n\nimport io.modelcontextprotocol.spec.McpClientTransport;\n\n/**\n * Interface for building McpClientTransport instances. Implementations of this interface are\n * responsible for constructing concrete McpClientTransport objects based on the provided connection\n * parameters.\n */\npublic interface McpTransportBuilder {\n /**\n * Builds an McpClientTransport based on the provided connection parameters.\n *\n * @param connectionParams The parameters required to configure the transport. The type of this\n * object determines the type of transport built.\n * @return An instance of McpClientTransport.\n * @throws IllegalArgumentException if the connectionParams are not supported or invalid.\n */\n McpClientTransport build(Object connectionParams);\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/sessions/ListEventsResponse.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\nimport com.google.adk.events.Event;\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\nimport java.util.List;\nimport java.util.Optional;\n\n/** Response for listing events. */\n@AutoValue\npublic abstract class ListEventsResponse {\n\n public abstract ImmutableList events();\n\n public abstract Optional nextPageToken();\n\n /** Builder for {@link ListEventsResponse}. */\n @AutoValue.Builder\n public abstract static class Builder {\n\n public abstract Builder events(List events);\n\n public abstract Builder nextPageToken(String nextPageToken);\n\n public abstract ListEventsResponse build();\n }\n\n public static Builder builder() {\n return new AutoValue_ListEventsResponse.Builder().events(ImmutableList.of());\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/LongRunningFunctionTool.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools;\n\nimport java.lang.reflect.Method;\n\n/** A function tool that returns the result asynchronously. */\npublic class LongRunningFunctionTool extends FunctionTool {\n\n public static LongRunningFunctionTool create(Method func) {\n return new LongRunningFunctionTool(func);\n }\n\n public static LongRunningFunctionTool create(Class cls, String methodName) {\n for (Method method : cls.getMethods()) {\n if (method.getName().equals(methodName)) {\n return create(method);\n }\n }\n throw new IllegalArgumentException(\n String.format(\"Method %s not found in class %s.\", methodName, cls.getName()));\n }\n\n public static LongRunningFunctionTool create(Object instance, String methodName) {\n Class cls = instance.getClass();\n for (Method method : cls.getMethods()) {\n if (method.getName().equals(methodName)) {\n return new LongRunningFunctionTool(instance, method);\n }\n }\n throw new IllegalArgumentException(\n String.format(\"Method %s not found in class %s.\", methodName, cls.getName()));\n }\n\n private LongRunningFunctionTool(Method func) {\n super(null, func, /* isLongRunning= */ true);\n }\n\n private LongRunningFunctionTool(Object instance, Method func) {\n super(instance, func, /* isLongRunning= */ true);\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/BaseFlow.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows;\n\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.events.Event;\nimport io.reactivex.rxjava3.core.Flowable;\n\n/** Interface for the execution flows to run a group of agents. */\npublic interface BaseFlow {\n\n /**\n * Run this flow.\n *\n *

To implement this method, the flow should follow the below requirements:\n *\n *

    \n *
  1. 1. `session` should be treated as immutable, DO NOT change it.\n *
  2. 2. The caller who trigger the flow is responsible for updating the session as the events\n * being generated. The subclass implementation will assume session is updated after each\n * yield event statement.\n *
  3. 3. A flow may spawn sub-agent flows depending on the agent definition.\n *
\n */\n Flowable run(InvocationContext invocationContext);\n\n default Flowable runLive(InvocationContext invocationContext) {\n throw new UnsupportedOperationException(\"Not implemented\");\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/agents/Instruction.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.agents;\n\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.function.Function;\n\n/**\n * Represents an instruction that can be provided to an agent to guide its behavior.\n *\n *

In the instructions, you should describe concisely what the agent will do, when it should\n * defer to other agents/tools, and how it should respond to the user.\n *\n *

Templating is supported using placeholders like {@code {variable_name}} or {@code\n * {artifact.artifact_name}}. These are replaced with values from the agent's session state or\n * loaded artifacts, respectively. For example, an instruction like {@code \"Translate the following\n * text to {language}: {user_query}\"} would substitute {@code {language}} and {@code {user_query}}\n * with their corresponding values from the session state.\n *\n *

Instructions can also be dynamically constructed using {@link Instruction.Provider}. This\n * allows for more complex logic where the instruction text is generated based on the current {@link\n * ReadonlyContext}. Additionally, an instruction could be built to include specific information\n * based on based on some external factors fetched during the Provider call like the current time,\n * the result of some API call, etc.\n */\npublic sealed interface Instruction permits Instruction.Static, Instruction.Provider {\n /** Plain instruction directly provided to the agent. */\n record Static(String instruction) implements Instruction {}\n\n /** Returns an instruction dynamically constructed from the given context. */\n record Provider(Function> getInstruction)\n implements Instruction {}\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/mcp/ConversionUtils.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools.mcp;\n\nimport com.google.adk.tools.BaseTool;\nimport com.google.genai.types.FunctionDeclaration;\nimport com.google.genai.types.Schema;\nimport io.modelcontextprotocol.spec.McpSchema;\nimport java.util.Optional;\n\n/** Utility class for converting between different representations of MCP tools. */\npublic final class ConversionUtils {\n\n public McpSchema.Tool adkToMcpToolType(BaseTool tool) {\n Optional toolDeclaration = tool.declaration();\n if (toolDeclaration.isEmpty()) {\n return new McpSchema.Tool(tool.name(), tool.description(), \"\");\n }\n Schema geminiSchema = toolDeclaration.get().parameters().get();\n return new McpSchema.Tool(tool.name(), tool.description(), geminiSchema.toJson());\n }\n\n private ConversionUtils() {}\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/utils/CollectionUtils.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.utils;\n\nimport com.google.common.collect.Iterables;\n\n/** Frequently used code snippets for collections. */\npublic final class CollectionUtils {\n\n /**\n * Checks if the given iterable is null or empty.\n *\n * @param iterable the iterable to check\n * @return true if the iterable is null or empty, false otherwise\n */\n public static boolean isNullOrEmpty(Iterable iterable) {\n return iterable == null || Iterables.isEmpty(iterable);\n }\n\n private CollectionUtils() {}\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/artifacts/ListArtifactsResponse.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.artifacts;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\nimport java.util.List;\n\n/** Response for listing artifacts. */\n@AutoValue\npublic abstract class ListArtifactsResponse {\n\n public abstract ImmutableList filenames();\n\n /** Builder for {@link ListArtifactsResponse}. */\n @AutoValue.Builder\n public abstract static class Builder {\n public abstract Builder filenames(List filenames);\n\n public abstract ListArtifactsResponse build();\n }\n\n public static Builder builder() {\n return new AutoValue_ListArtifactsResponse.Builder();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/ToolPredicate.java", "package com.google.adk.tools;\n\nimport com.google.adk.agents.ReadonlyContext;\nimport java.util.Optional;\n\n/**\n * Functional interface to decide whether a tool should be exposed to the LLM based on the current\n * context.\n */\n@FunctionalInterface\npublic interface ToolPredicate {\n /**\n * Decides if the given tool is selected.\n *\n * @param tool The tool to check.\n * @param readonlyContext The current context.\n * @return true if the tool should be selected, false otherwise.\n */\n boolean test(BaseTool tool, Optional readonlyContext);\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/ExitLoopTool.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools;\n\n/** Exits the loop. */\npublic final class ExitLoopTool {\n public static void exitLoop(ToolContext toolContext) {\n // Exits the loop.\n // Call this function only when you are instructed to do so.\n toolContext.setActions(toolContext.actions().toBuilder().escalate(true).build());\n }\n\n private ExitLoopTool() {}\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/sessions/GetSessionConfig.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\nimport com.google.auto.value.AutoValue;\nimport java.time.Instant;\nimport java.util.Optional;\n\n/** Configuration for getting a session. */\n@AutoValue\npublic abstract class GetSessionConfig {\n\n public abstract Optional numRecentEvents();\n\n public abstract Optional afterTimestamp();\n\n /** Builder for {@link GetSessionConfig}. */\n @AutoValue.Builder\n public abstract static class Builder {\n\n public abstract Builder numRecentEvents(int numRecentEvents);\n\n public abstract Builder afterTimestamp(Instant afterTimestamp);\n\n public abstract GetSessionConfig build();\n }\n\n public static Builder builder() {\n return new AutoValue_GetSessionConfig.Builder();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/sessions/HttpApiResponse.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\nimport okhttp3.Response;\nimport okhttp3.ResponseBody;\n\n/** Wraps a real HTTP response to expose the methods needed by the GenAI SDK. */\npublic final class HttpApiResponse extends ApiResponse {\n\n private final Response response;\n\n /** Constructs a HttpApiResponse instance with the response. */\n public HttpApiResponse(Response response) {\n this.response = response;\n }\n\n /** Returns the HttpEntity from the response. */\n @Override\n public ResponseBody getResponseBody() {\n return response.body();\n }\n\n /** Closes the Http response. */\n @Override\n public void close() {\n response.close();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/Version.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk;\n\n/**\n * Tracks the current ADK version. Useful for tracking headers. Kept as a string literal to avoid\n * coupling with the build system.\n */\npublic final class Version {\n // Don't touch this, release-please should keep it up to date.\n public static final String JAVA_ADK_VERSION = \"0.2.1-SNAPSHOT\";\n\n private Version() {}\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/exceptions/LlmCallsLimitExceededException.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.google.adk.exceptions;\n\n/** An error indicating that the limit for calls to the LLM has been exceeded. */\npublic final class LlmCallsLimitExceededException extends Exception {\n\n public LlmCallsLimitExceededException(String message) {\n super(message);\n }\n}\n"], ["/adk-java/dev/src/main/java/com/google/adk/web/config/AgentLoadingProperties.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.web.config;\n\nimport org.springframework.boot.context.properties.ConfigurationProperties;\nimport org.springframework.stereotype.Component;\n\n/** Properties for loading agents. */\n@Component\n@ConfigurationProperties(prefix = \"adk.agents\")\npublic class AgentLoadingProperties {\n private String sourceDir = \"src/main/java\";\n private String compileClasspath;\n\n public String getSourceDir() {\n return sourceDir;\n }\n\n public void setSourceDir(String sourceDir) {\n this.sourceDir = sourceDir;\n }\n\n public String getCompileClasspath() {\n return compileClasspath;\n }\n\n public void setCompileClasspath(String compileClasspath) {\n this.compileClasspath = compileClasspath;\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/runner/InMemoryRunner.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.runner;\n\nimport com.google.adk.agents.BaseAgent;\nimport com.google.adk.artifacts.InMemoryArtifactService;\nimport com.google.adk.sessions.InMemorySessionService;\n\n/** The class for the in-memory GenAi runner, using in-memory artifact and session services. */\npublic class InMemoryRunner extends Runner {\n\n public InMemoryRunner(BaseAgent agent) {\n // TODO: Change the default appName to InMemoryRunner to align with adk python.\n // Check the dev UI in case we break something there.\n this(agent, /* appName= */ agent.name());\n }\n\n public InMemoryRunner(BaseAgent agent, String appName) {\n super(agent, appName, new InMemoryArtifactService(), new InMemorySessionService());\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/Annotations.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools;\n\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.ElementType.PARAMETER;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\n/** Annotations for tools. */\npublic final class Annotations {\n\n /** The annotation for binding the 'Schema' input. */\n @Target({METHOD, PARAMETER})\n @Retention(RetentionPolicy.RUNTIME)\n public @interface Schema {\n String name() default \"\";\n\n String description() default \"\";\n }\n\n private Annotations() {}\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/network/ApiResponse.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.network;\n\nimport okhttp3.ResponseBody;\n\n/** The API response contains a response to a call to the GenAI APIs. */\npublic abstract class ApiResponse implements AutoCloseable {\n /** Gets the ResponseBody. */\n public abstract ResponseBody getEntity();\n\n @Override\n public abstract void close();\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/sessions/ApiResponse.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\nimport okhttp3.ResponseBody;\n\n/** The API response contains a response to a call to the GenAI APIs. */\npublic abstract class ApiResponse implements AutoCloseable {\n /** Gets the HttpEntity. */\n public abstract ResponseBody getResponseBody();\n\n @Override\n public abstract void close();\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/sessions/SessionNotFoundException.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\n/** Indicates that a requested session could not be found. */\npublic class SessionNotFoundException extends SessionException {\n\n public SessionNotFoundException(String message) {\n super(message);\n }\n\n public SessionNotFoundException(String message, Throwable cause) {\n super(message, cause);\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/sessions/SessionException.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\n/** Represents a general error that occurred during session management operations. */\npublic class SessionException extends RuntimeException {\n\n public SessionException(String message) {\n super(message);\n }\n\n public SessionException(String message, Throwable cause) {\n super(message, cause);\n }\n\n public SessionException(Throwable cause) {\n super(cause);\n }\n}\n"]], "task_instance_info": {"created_time": "2025-08-20 20:39:51", "created_task_model": "DeepSeek-R1", "function_skeleton": "private List stripThoughts (List originalContents) {}", "code_description": "This code segment functions to: Filter elements from a structured data collection by removing entries that match a specific annotation pattern before subsequent processing."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```java\n[TASK_BEGIN]\nprivate List stripThoughts(List originalContents) {\n return originalContents.stream()\n .map(content -> {\n if (content.parts().isEmpty()) {\n return content;\n }\n \n ImmutableList filteredParts = content.parts().get().stream()\n .filter(part -> {\n // Keep part if it doesn't have a thought, or has a thought along with other content\n boolean hasThought = part.thought().isPresent();\n boolean hasContent = part.text().isPresent()\n || part.inlineData().isPresent()\n || part.fileData().isPresent()\n || part.functionResponse().isPresent()\n || part.functionCall().isPresent();\n \n return !hasThought || (hasThought && hasContent);\n })\n .collect(toImmutableList());\n \n return content.toBuilder().parts(filteredParts).build();\n })\n .collect(toImmutableList());\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 20-40-23"}, "editdistance_info": {"edit_distance": 25.1497, "calculate_time": "2025-08-20 20:40:23", "true_code_clean": "private List stripThoughts(List originalContents) {\n List updatedContents = new ArrayList<>();\n for (Content content : originalContents) {\n ImmutableList nonThoughtParts =\n content.parts().orElse(ImmutableList.of()).stream()\n .filter(part -> part.thought().map(isThought -> !isThought).orElse(true))\n .collect(toImmutableList());\n updatedContents.add(content.toBuilder().parts(nonThoughtParts).build());\n }\n return updatedContents;\n }", "predict_code_clean": "private List stripThoughts(List originalContents) {\n return originalContents.stream()\n .map(content -> {\n if (content.parts().isEmpty()) {\n return content;\n }\n ImmutableList filteredParts = content.parts().get().stream()\n .filter(part -> {\n boolean hasThought = part.thought().isPresent();\n boolean hasContent = part.text().isPresent()\n || part.inlineData().isPresent()\n || part.fileData().isPresent()\n || part.functionResponse().isPresent()\n || part.functionCall().isPresent();\n return !hasThought || (hasThought && hasContent);\n })\n .collect(toImmutableList());\n return content.toBuilder().parts(filteredParts).build();\n })\n .collect(toImmutableList());\n}"}} {"repo_name": "adk-java", "file_name": "/adk-java/core/src/main/java/com/google/adk/sessions/InMemorySessionService.java", "inference_info": {"prefix_code": "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\nimport static java.util.stream.Collectors.toCollection;\n\nimport com.google.adk.events.Event;\nimport com.google.adk.events.EventActions;\nimport com.google.common.collect.ImmutableList;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport io.reactivex.rxjava3.core.Completable;\nimport io.reactivex.rxjava3.core.Maybe;\nimport io.reactivex.rxjava3.core.Single;\nimport java.time.Instant;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.Optional;\nimport java.util.UUID;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentMap;\nimport org.jspecify.annotations.Nullable;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * An in-memory implementation of {@link BaseSessionService} assuming {@link Session} objects are\n * mutable regarding their state map, events list, and last update time.\n *\n *

This implementation stores sessions, user state, and app state directly in memory using\n * concurrent maps for basic thread safety. It is suitable for testing or single-node deployments\n * where persistence is not required.\n *\n *

Note: State merging (app/user state prefixed with {@code _app_} / {@code _user_}) occurs\n * during retrieval operations ({@code getSession}, {@code createSession}).\n */\npublic final class InMemorySessionService implements BaseSessionService {\n\n private static final Logger logger = LoggerFactory.getLogger(InMemorySessionService.class);\n\n // Structure: appName -> userId -> sessionId -> Session\n private final ConcurrentMap>>\n sessions;\n // Structure: appName -> userId -> stateKey -> stateValue\n private final ConcurrentMap>>\n userState;\n // Structure: appName -> stateKey -> stateValue\n private final ConcurrentMap> appState;\n\n /** Creates a new instance of the in-memory session service with empty storage. */\n public InMemorySessionService() {\n this.sessions = new ConcurrentHashMap<>();\n this.userState = new ConcurrentHashMap<>();\n this.appState = new ConcurrentHashMap<>();\n }\n\n @Override\n public Single createSession(\n String appName,\n String userId,\n @Nullable ConcurrentMap state,\n @Nullable String sessionId) {\n Objects.requireNonNull(appName, \"appName cannot be null\");\n Objects.requireNonNull(userId, \"userId cannot be null\");\n\n String resolvedSessionId =\n Optional.ofNullable(sessionId)\n .map(String::trim)\n .filter(s -> !s.isEmpty())\n .orElseGet(() -> UUID.randomUUID().toString());\n\n // Ensure state map and events list are mutable for the new session\n ConcurrentMap initialState =\n (state == null) ? new ConcurrentHashMap<>() : new ConcurrentHashMap<>(state);\n List initialEvents = new ArrayList<>();\n\n // Assuming Session constructor or setters allow setting these mutable collections\n Session newSession =\n Session.builder(resolvedSessionId)\n .appName(appName)\n .userId(userId)\n .state(initialState)\n .events(initialEvents)\n .lastUpdateTime(Instant.now())\n .build();\n\n sessions\n .computeIfAbsent(appName, k -> new ConcurrentHashMap<>())\n .computeIfAbsent(userId, k -> new ConcurrentHashMap<>())\n .put(resolvedSessionId, newSession);\n\n // Create a mutable copy for the return value\n Session returnCopy = copySession(newSession);\n // Merge state into the copy before returning\n return Single.just(mergeWithGlobalState(appName, userId, returnCopy));\n }\n\n ", "suffix_code": "\n\n // Helper to get event timestamp as epoch seconds\n private long getEventTimestampEpochSeconds(Event event) {\n return event.timestamp() / 1000L;\n }\n\n @Override\n public Single listSessions(String appName, String userId) {\n Objects.requireNonNull(appName, \"appName cannot be null\");\n Objects.requireNonNull(userId, \"userId cannot be null\");\n\n Map userSessionsMap =\n sessions.getOrDefault(appName, new ConcurrentHashMap<>()).get(userId);\n\n if (userSessionsMap == null || userSessionsMap.isEmpty()) {\n return Single.just(ListSessionsResponse.builder().build());\n }\n\n // Create copies with empty events and state for the response\n List sessionCopies =\n userSessionsMap.values().stream()\n .map(this::copySessionMetadata)\n .collect(toCollection(ArrayList::new));\n\n return Single.just(ListSessionsResponse.builder().sessions(sessionCopies).build());\n }\n\n @Override\n public Completable deleteSession(String appName, String userId, String sessionId) {\n Objects.requireNonNull(appName, \"appName cannot be null\");\n Objects.requireNonNull(userId, \"userId cannot be null\");\n Objects.requireNonNull(sessionId, \"sessionId cannot be null\");\n\n ConcurrentMap userSessionsMap =\n sessions.getOrDefault(appName, new ConcurrentHashMap<>()).get(userId);\n\n if (userSessionsMap != null) {\n userSessionsMap.remove(sessionId);\n }\n return Completable.complete();\n }\n\n @Override\n public Single listEvents(String appName, String userId, String sessionId) {\n Objects.requireNonNull(appName, \"appName cannot be null\");\n Objects.requireNonNull(userId, \"userId cannot be null\");\n Objects.requireNonNull(sessionId, \"sessionId cannot be null\");\n\n Session storedSession =\n sessions\n .getOrDefault(appName, new ConcurrentHashMap<>())\n .getOrDefault(userId, new ConcurrentHashMap<>())\n .get(sessionId);\n\n if (storedSession == null) {\n return Single.just(ListEventsResponse.builder().build());\n }\n\n ImmutableList eventsCopy = ImmutableList.copyOf(storedSession.events());\n return Single.just(ListEventsResponse.builder().events(eventsCopy).build());\n }\n\n @CanIgnoreReturnValue\n @Override\n public Single appendEvent(Session session, Event event) {\n Objects.requireNonNull(session, \"session cannot be null\");\n Objects.requireNonNull(event, \"event cannot be null\");\n Objects.requireNonNull(session.appName(), \"session.appName cannot be null\");\n Objects.requireNonNull(session.userId(), \"session.userId cannot be null\");\n Objects.requireNonNull(session.id(), \"session.id cannot be null\");\n\n String appName = session.appName();\n String userId = session.userId();\n String sessionId = session.id();\n\n // --- Update User/App State (Same as before) ---\n EventActions actions = event.actions();\n if (actions != null) {\n Map stateDelta = actions.stateDelta();\n if (stateDelta != null && !stateDelta.isEmpty()) {\n stateDelta.forEach(\n (key, value) -> {\n if (key.startsWith(State.APP_PREFIX)) {\n String appStateKey = key.substring(State.APP_PREFIX.length());\n appState\n .computeIfAbsent(appName, k -> new ConcurrentHashMap<>())\n .put(appStateKey, value);\n } else if (key.startsWith(State.USER_PREFIX)) {\n String userStateKey = key.substring(State.USER_PREFIX.length());\n userState\n .computeIfAbsent(appName, k -> new ConcurrentHashMap<>())\n .computeIfAbsent(userId, k -> new ConcurrentHashMap<>())\n .put(userStateKey, value);\n }\n });\n }\n }\n\n BaseSessionService.super.appendEvent(session, event);\n session.lastUpdateTime(getInstantFromEvent(event));\n\n // --- Update the session stored in this service ---\n sessions\n .getOrDefault(appName, new ConcurrentHashMap<>())\n .getOrDefault(userId, new ConcurrentHashMap<>())\n .put(sessionId, session);\n\n return Single.just(event);\n }\n\n /** Converts an event's timestamp to an Instant. Adapt based on actual Event structure. */\n // TODO: have Event.timestamp() return Instant directly\n private Instant getInstantFromEvent(Event event) {\n double epochSeconds = getEventTimestampEpochSeconds(event);\n long seconds = (long) epochSeconds;\n long nanos = (long) ((epochSeconds % 1.0) * 1_000_000_000L);\n return Instant.ofEpochSecond(seconds, nanos);\n }\n\n /**\n * Creates a shallow copy of the session, but with deep copies of the mutable state map and events\n * list. Assumes Session provides necessary getters and a suitable constructor/setters.\n *\n * @param original The session to copy.\n * @return A new Session instance with copied data, including mutable collections.\n */\n private Session copySession(Session original) {\n return Session.builder(original.id())\n .appName(original.appName())\n .userId(original.userId())\n .state(new ConcurrentHashMap<>(original.state()))\n .events(new ArrayList<>(original.events()))\n .lastUpdateTime(original.lastUpdateTime())\n .build();\n }\n\n /**\n * Creates a copy of the session containing only metadata fields (ID, appName, userId, timestamp).\n * State and Events are explicitly *not* copied.\n *\n * @param original The session whose metadata to copy.\n * @return A new Session instance with only metadata fields populated.\n */\n private Session copySessionMetadata(Session original) {\n return Session.builder(original.id())\n .appName(original.appName())\n .userId(original.userId())\n .lastUpdateTime(original.lastUpdateTime())\n .build();\n }\n\n /**\n * Merges the app-specific and user-specific state into the provided *mutable* session's state\n * map.\n *\n * @param appName The application name.\n * @param userId The user ID.\n * @param session The mutable session whose state map will be augmented.\n * @return The same session instance passed in, now with merged state.\n */\n @CanIgnoreReturnValue\n private Session mergeWithGlobalState(String appName, String userId, Session session) {\n Map sessionState = session.state();\n\n // Merge App State directly into the session's state map\n appState\n .getOrDefault(appName, new ConcurrentHashMap())\n .forEach((key, value) -> sessionState.put(State.APP_PREFIX + key, value));\n\n userState\n .getOrDefault(appName, new ConcurrentHashMap<>())\n .getOrDefault(userId, new ConcurrentHashMap<>())\n .forEach((key, value) -> sessionState.put(State.USER_PREFIX + key, value));\n\n return session;\n }\n}\n", "middle_code": "@Override\n public Maybe getSession(\n String appName, String userId, String sessionId, Optional configOpt) {\n Objects.requireNonNull(appName, \"appName cannot be null\");\n Objects.requireNonNull(userId, \"userId cannot be null\");\n Objects.requireNonNull(sessionId, \"sessionId cannot be null\");\n Objects.requireNonNull(configOpt, \"configOpt cannot be null\");\n Session storedSession =\n sessions\n .getOrDefault(appName, new ConcurrentHashMap<>())\n .getOrDefault(userId, new ConcurrentHashMap<>())\n .get(sessionId);\n if (storedSession == null) {\n return Maybe.empty();\n }\n Session sessionCopy = copySession(storedSession);\n GetSessionConfig config = configOpt.orElse(GetSessionConfig.builder().build());\n List eventsInCopy = sessionCopy.events();\n config\n .numRecentEvents()\n .ifPresent(\n num -> {\n if (!eventsInCopy.isEmpty() && num < eventsInCopy.size()) {\n List eventsToRemove = eventsInCopy.subList(0, eventsInCopy.size() - num);\n eventsToRemove.clear(); \n }\n });\n if (config.numRecentEvents().isEmpty() && config.afterTimestamp().isPresent()) {\n Instant threshold = config.afterTimestamp().get();\n eventsInCopy.removeIf(\n event -> getEventTimestampEpochSeconds(event) < threshold.getEpochSecond());\n }\n return Maybe.just(mergeWithGlobalState(appName, userId, sessionCopy));\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "java", "sub_task_type": null}, "context_code": [["/adk-java/core/src/main/java/com/google/adk/sessions/VertexAiSessionService.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\nimport static com.google.common.base.Strings.nullToEmpty;\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static java.util.stream.Collectors.toCollection;\n\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.google.adk.JsonBaseModel;\nimport com.google.adk.events.Event;\nimport com.google.adk.events.EventActions;\nimport com.google.auth.oauth2.GoogleCredentials;\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.FinishReason;\nimport com.google.genai.types.GroundingMetadata;\nimport com.google.genai.types.HttpOptions;\nimport com.google.genai.types.Part;\nimport io.reactivex.rxjava3.core.Completable;\nimport io.reactivex.rxjava3.core.Maybe;\nimport io.reactivex.rxjava3.core.Single;\nimport java.io.IOException;\nimport java.io.UncheckedIOException;\nimport java.time.Instant;\nimport java.util.ArrayList;\nimport java.util.Comparator;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentMap;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport javax.annotation.Nullable;\nimport okhttp3.ResponseBody;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/** Connects to the managed Vertex AI Session Service. */\n/** TODO: Use the genai HttpApiClient and ApiResponse methods once they are public. */\npublic final class VertexAiSessionService implements BaseSessionService {\n private static final int MAX_RETRY_ATTEMPTS = 5;\n private static final ObjectMapper objectMapper = JsonBaseModel.getMapper();\n private static final Logger logger = LoggerFactory.getLogger(VertexAiSessionService.class);\n\n private final HttpApiClient apiClient;\n\n /**\n * Creates a new instance of the Vertex AI Session Service with a custom ApiClient for testing.\n */\n public VertexAiSessionService(String project, String location, HttpApiClient apiClient) {\n this.apiClient = apiClient;\n }\n\n /** Creates a session service with default configuration. */\n public VertexAiSessionService() {\n this.apiClient =\n new HttpApiClient(Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty());\n }\n\n /** Creates a session service with specified project, location, credentials, and HTTP options. */\n public VertexAiSessionService(\n String project,\n String location,\n Optional credentials,\n Optional httpOptions) {\n this.apiClient =\n new HttpApiClient(Optional.of(project), Optional.of(location), credentials, httpOptions);\n }\n\n /**\n * Parses the JSON response body from the given API response.\n *\n * @throws UncheckedIOException if parsing fails.\n */\n private static JsonNode getJsonResponse(ApiResponse apiResponse) {\n try {\n ResponseBody responseBody = apiResponse.getResponseBody();\n return objectMapper.readTree(responseBody.string());\n } catch (IOException e) {\n throw new UncheckedIOException(e);\n }\n }\n\n @Override\n public Single createSession(\n String appName,\n String userId,\n @Nullable ConcurrentMap state,\n @Nullable String sessionId) {\n\n String reasoningEngineId = parseReasoningEngineId(appName);\n ConcurrentHashMap sessionJsonMap = new ConcurrentHashMap<>();\n sessionJsonMap.put(\"userId\", userId);\n if (state != null) {\n sessionJsonMap.put(\"sessionState\", state);\n }\n\n ApiResponse apiResponse;\n try {\n apiResponse =\n apiClient.request(\n \"POST\",\n \"reasoningEngines/\" + reasoningEngineId + \"/sessions\",\n objectMapper.writeValueAsString(sessionJsonMap));\n } catch (IOException e) {\n throw new UncheckedIOException(e);\n }\n\n logger.debug(\"Create Session response {}\", apiResponse.getResponseBody());\n String sessionName = \"\";\n String operationId = \"\";\n String sessId = nullToEmpty(sessionId);\n if (apiResponse.getResponseBody() != null) {\n JsonNode jsonResponse = getJsonResponse(apiResponse);\n sessionName = jsonResponse.get(\"name\").asText();\n List parts = Splitter.on('/').splitToList(sessionName);\n sessId = parts.get(parts.size() - 3);\n operationId = Iterables.getLast(parts);\n }\n for (int i = 0; i < MAX_RETRY_ATTEMPTS; i++) {\n ApiResponse lroResponse = apiClient.request(\"GET\", \"operations/\" + operationId, \"\");\n JsonNode jsonResponse = getJsonResponse(lroResponse);\n if (jsonResponse.get(\"done\") != null) {\n break;\n }\n try {\n SECONDS.sleep(1);\n } catch (InterruptedException e) {\n logger.warn(\"Error during sleep\", e);\n }\n }\n\n ApiResponse getSessionApiResponse =\n apiClient.request(\n \"GET\", \"reasoningEngines/\" + reasoningEngineId + \"/sessions/\" + sessId, \"\");\n JsonNode getSessionResponseMap = getJsonResponse(getSessionApiResponse);\n Instant updateTimestamp = Instant.parse(getSessionResponseMap.get(\"updateTime\").asText());\n ConcurrentMap sessionState = null;\n if (getSessionResponseMap != null && getSessionResponseMap.has(\"sessionState\")) {\n JsonNode sessionStateNode = getSessionResponseMap.get(\"sessionState\");\n if (sessionStateNode != null) {\n sessionState =\n objectMapper.convertValue(\n sessionStateNode, new TypeReference>() {});\n }\n }\n return Single.just(\n Session.builder(sessId)\n .appName(appName)\n .userId(userId)\n .lastUpdateTime(updateTimestamp)\n .state(sessionState == null ? new ConcurrentHashMap<>() : sessionState)\n .build());\n }\n\n @Override\n public Single listSessions(String appName, String userId) {\n String reasoningEngineId = parseReasoningEngineId(appName);\n\n ApiResponse apiResponse =\n apiClient.request(\n \"GET\",\n \"reasoningEngines/\" + reasoningEngineId + \"/sessions?filter=user_id=\" + userId,\n \"\");\n\n // Handles empty response case\n if (apiResponse.getResponseBody() == null) {\n return Single.just(ListSessionsResponse.builder().build());\n }\n\n JsonNode listSessionsResponseMap = getJsonResponse(apiResponse);\n List> apiSessions =\n objectMapper.convertValue(\n listSessionsResponseMap.get(\"sessions\"),\n new TypeReference>>() {});\n\n List sessions = new ArrayList<>();\n for (Map apiSession : apiSessions) {\n String sessionId =\n Iterables.getLast(Splitter.on('/').splitToList((String) apiSession.get(\"name\")));\n Instant updateTimestamp = Instant.parse((String) apiSession.get(\"updateTime\"));\n Session session =\n Session.builder(sessionId)\n .appName(appName)\n .userId(userId)\n .state(new ConcurrentHashMap<>())\n .lastUpdateTime(updateTimestamp)\n .build();\n sessions.add(session);\n }\n return Single.just(ListSessionsResponse.builder().sessions(sessions).build());\n }\n\n @Override\n public Single listEvents(String appName, String userId, String sessionId) {\n String reasoningEngineId = parseReasoningEngineId(appName);\n ApiResponse apiResponse =\n apiClient.request(\n \"GET\",\n \"reasoningEngines/\" + reasoningEngineId + \"/sessions/\" + sessionId + \"/events\",\n \"\");\n\n logger.debug(\"List events response {}\", apiResponse);\n\n if (apiResponse.getResponseBody() == null) {\n return Single.just(ListEventsResponse.builder().build());\n }\n\n JsonNode sessionEventsNode = getJsonResponse(apiResponse).get(\"sessionEvents\");\n if (sessionEventsNode == null || sessionEventsNode.isEmpty()) {\n return Single.just(ListEventsResponse.builder().events(new ArrayList<>()).build());\n }\n return Single.just(\n ListEventsResponse.builder()\n .events(\n objectMapper\n .convertValue(\n sessionEventsNode,\n new TypeReference>>() {})\n .stream()\n .map(event -> fromApiEvent(event))\n .collect(toCollection(ArrayList::new)))\n .build());\n }\n\n @Override\n public Maybe getSession(\n String appName, String userId, String sessionId, Optional config) {\n String reasoningEngineId = parseReasoningEngineId(appName);\n ApiResponse apiResponse =\n apiClient.request(\n \"GET\", \"reasoningEngines/\" + reasoningEngineId + \"/sessions/\" + sessionId, \"\");\n JsonNode getSessionResponseMap = getJsonResponse(apiResponse);\n\n if (getSessionResponseMap == null) {\n return Maybe.empty();\n }\n\n String sessId =\n Optional.ofNullable(getSessionResponseMap.get(\"name\"))\n .map(name -> Iterables.getLast(Splitter.on('/').splitToList(name.asText())))\n .orElse(sessionId);\n Instant updateTimestamp =\n Optional.ofNullable(getSessionResponseMap.get(\"updateTime\"))\n .map(updateTime -> Instant.parse(updateTime.asText()))\n .orElse(null);\n\n ConcurrentMap sessionState = new ConcurrentHashMap<>();\n if (getSessionResponseMap != null && getSessionResponseMap.has(\"sessionState\")) {\n sessionState.putAll(\n objectMapper.convertValue(\n getSessionResponseMap.get(\"sessionState\"),\n new TypeReference>() {}));\n }\n\n return listEvents(appName, userId, sessionId)\n .map(\n response -> {\n Session.Builder sessionBuilder =\n Session.builder(sessId)\n .appName(appName)\n .userId(userId)\n .lastUpdateTime(updateTimestamp)\n .state(sessionState);\n List events = response.events();\n if (events.isEmpty()) {\n return sessionBuilder.build();\n }\n events =\n events.stream()\n .filter(\n event ->\n updateTimestamp == null\n || Instant.ofEpochMilli(event.timestamp())\n .isBefore(updateTimestamp))\n .sorted(Comparator.comparing(Event::timestamp))\n .collect(toCollection(ArrayList::new));\n\n if (config.isPresent()) {\n if (config.get().numRecentEvents().isPresent()) {\n int numRecentEvents = config.get().numRecentEvents().get();\n if (events.size() > numRecentEvents) {\n events = events.subList(events.size() - numRecentEvents, events.size());\n }\n } else if (config.get().afterTimestamp().isPresent()) {\n Instant afterTimestamp = config.get().afterTimestamp().get();\n int i = events.size() - 1;\n while (i >= 0) {\n if (Instant.ofEpochMilli(events.get(i).timestamp()).isBefore(afterTimestamp)) {\n break;\n }\n i -= 1;\n }\n if (i >= 0) {\n events = events.subList(i, events.size());\n }\n }\n }\n return sessionBuilder.events(events).build();\n })\n .toMaybe();\n }\n\n @Override\n public Completable deleteSession(String appName, String userId, String sessionId) {\n String reasoningEngineId = parseReasoningEngineId(appName);\n ApiResponse unused =\n apiClient.request(\n \"DELETE\", \"reasoningEngines/\" + reasoningEngineId + \"/sessions/\" + sessionId, \"\");\n return Completable.complete();\n }\n\n @Override\n public Single appendEvent(Session session, Event event) {\n BaseSessionService.super.appendEvent(session, event);\n\n String reasoningEngineId = parseReasoningEngineId(session.appName());\n ApiResponse response =\n apiClient.request(\n \"POST\",\n \"reasoningEngines/\" + reasoningEngineId + \"/sessions/\" + session.id() + \":appendEvent\",\n convertEventToJson(event));\n // TODO(b/414263934)): Improve error handling for appendEvent.\n try {\n if (response.getResponseBody().string().contains(\"com.google.genai.errors.ClientException\")) {\n logger.warn(\"Failed to append event: \", event);\n }\n } catch (IOException e) {\n throw new UncheckedIOException(e);\n }\n\n response.close();\n return Single.just(event);\n }\n\n /**\n * Converts an {@link Event} to its JSON string representation for API transmission.\n *\n * @return JSON string of the event.\n * @throws UncheckedIOException if serialization fails.\n */\n static String convertEventToJson(Event event) {\n Map metadataJson = new HashMap<>();\n metadataJson.put(\"partial\", event.partial());\n metadataJson.put(\"turnComplete\", event.turnComplete());\n metadataJson.put(\"interrupted\", event.interrupted());\n metadataJson.put(\"branch\", event.branch().orElse(null));\n metadataJson.put(\n \"long_running_tool_ids\",\n event.longRunningToolIds() != null ? event.longRunningToolIds().orElse(null) : null);\n if (event.groundingMetadata() != null) {\n metadataJson.put(\"grounding_metadata\", event.groundingMetadata());\n }\n\n Map eventJson = new HashMap<>();\n eventJson.put(\"author\", event.author());\n eventJson.put(\"invocationId\", event.invocationId());\n eventJson.put(\n \"timestamp\",\n new HashMap<>(\n ImmutableMap.of(\n \"seconds\",\n event.timestamp() / 1000,\n \"nanos\",\n (event.timestamp() % 1000) * 1000000)));\n if (event.errorCode().isPresent()) {\n eventJson.put(\"errorCode\", event.errorCode());\n }\n if (event.errorMessage().isPresent()) {\n eventJson.put(\"errorMessage\", event.errorMessage());\n }\n eventJson.put(\"eventMetadata\", metadataJson);\n\n if (event.actions() != null) {\n Map actionsJson = new HashMap<>();\n actionsJson.put(\"skipSummarization\", event.actions().skipSummarization());\n actionsJson.put(\"stateDelta\", event.actions().stateDelta());\n actionsJson.put(\"artifactDelta\", event.actions().artifactDelta());\n actionsJson.put(\"transferAgent\", event.actions().transferToAgent());\n actionsJson.put(\"escalate\", event.actions().escalate());\n actionsJson.put(\"requestedAuthConfigs\", event.actions().requestedAuthConfigs());\n eventJson.put(\"actions\", actionsJson);\n }\n if (event.content().isPresent()) {\n eventJson.put(\"content\", SessionUtils.encodeContent(event.content().get()));\n }\n if (event.errorCode().isPresent()) {\n eventJson.put(\"errorCode\", event.errorCode().get());\n }\n if (event.errorMessage().isPresent()) {\n eventJson.put(\"errorMessage\", event.errorMessage().get());\n }\n try {\n return objectMapper.writeValueAsString(eventJson);\n } catch (JsonProcessingException e) {\n throw new UncheckedIOException(e);\n }\n }\n\n /**\n * Converts a raw value to a {@link Content} object.\n *\n * @return parsed {@link Content}, or {@code null} if conversion fails.\n */\n @Nullable\n @SuppressWarnings(\"unchecked\")\n private static Content convertMapToContent(Object rawContentValue) {\n if (rawContentValue == null) {\n return null;\n }\n\n if (rawContentValue instanceof Map) {\n Map contentMap = (Map) rawContentValue;\n try {\n return objectMapper.convertValue(contentMap, Content.class);\n } catch (IllegalArgumentException e) {\n logger.warn(\"Error converting Map to Content\", e);\n return null;\n }\n } else {\n logger.warn(\n \"Unexpected type for 'content' in apiEvent: {}\", rawContentValue.getClass().getName());\n return null;\n }\n }\n\n /**\n * Extracts the reasoning engine ID from the given app name or full resource name.\n *\n * @return reasoning engine ID.\n * @throws IllegalArgumentException if format is invalid.\n */\n static String parseReasoningEngineId(String appName) {\n if (appName.matches(\"\\\\d+\")) {\n return appName;\n }\n\n Matcher matcher = APP_NAME_PATTERN.matcher(appName);\n\n if (!matcher.matches()) {\n throw new IllegalArgumentException(\n \"App name \"\n + appName\n + \" is not valid. It should either be the full\"\n + \" ReasoningEngine resource name, or the reasoning engine id.\");\n }\n\n return matcher.group(matcher.groupCount());\n }\n\n /**\n * Converts raw API event data into an {@link Event} object.\n *\n * @return parsed {@link Event}.\n */\n @SuppressWarnings(\"unchecked\")\n static Event fromApiEvent(Map apiEvent) {\n EventActions eventActions = new EventActions();\n if (apiEvent.get(\"actions\") != null) {\n Map actionsMap = (Map) apiEvent.get(\"actions\");\n eventActions.setSkipSummarization(\n Optional.ofNullable(actionsMap.get(\"skipSummarization\")).map(value -> (Boolean) value));\n eventActions.setStateDelta(\n actionsMap.get(\"stateDelta\") != null\n ? new ConcurrentHashMap<>((Map) actionsMap.get(\"stateDelta\"))\n : new ConcurrentHashMap<>());\n eventActions.setArtifactDelta(\n actionsMap.get(\"artifactDelta\") != null\n ? new ConcurrentHashMap<>((Map) actionsMap.get(\"artifactDelta\"))\n : new ConcurrentHashMap<>());\n eventActions.setTransferToAgent(\n actionsMap.get(\"transferAgent\") != null\n ? (String) actionsMap.get(\"transferAgent\")\n : null);\n eventActions.setEscalate(\n Optional.ofNullable(actionsMap.get(\"escalate\")).map(value -> (Boolean) value));\n eventActions.setRequestedAuthConfigs(\n Optional.ofNullable(actionsMap.get(\"requestedAuthConfigs\"))\n .map(VertexAiSessionService::asConcurrentMapOfConcurrentMaps)\n .orElse(new ConcurrentHashMap<>()));\n }\n\n Event event =\n Event.builder()\n .id((String) Iterables.getLast(Splitter.on('/').split(apiEvent.get(\"name\").toString())))\n .invocationId((String) apiEvent.get(\"invocationId\"))\n .author((String) apiEvent.get(\"author\"))\n .actions(eventActions)\n .content(\n Optional.ofNullable(apiEvent.get(\"content\"))\n .map(VertexAiSessionService::convertMapToContent)\n .map(SessionUtils::decodeContent)\n .orElse(null))\n .timestamp(convertToInstant(apiEvent.get(\"timestamp\")).toEpochMilli())\n .errorCode(\n Optional.ofNullable(apiEvent.get(\"errorCode\"))\n .map(value -> new FinishReason((String) value)))\n .errorMessage(\n Optional.ofNullable(apiEvent.get(\"errorMessage\")).map(value -> (String) value))\n .branch(Optional.ofNullable(apiEvent.get(\"branch\")).map(value -> (String) value))\n .build();\n // TODO(b/414263934): Add Event branch and grounding metadata for python parity.\n if (apiEvent.get(\"eventMetadata\") != null) {\n Map eventMetadata = (Map) apiEvent.get(\"eventMetadata\");\n List longRunningToolIdsList = (List) eventMetadata.get(\"longRunningToolIds\");\n\n GroundingMetadata groundingMetadata = null;\n Object rawGroundingMetadata = eventMetadata.get(\"groundingMetadata\");\n if (rawGroundingMetadata != null) {\n groundingMetadata =\n objectMapper.convertValue(rawGroundingMetadata, GroundingMetadata.class);\n }\n\n event =\n event.toBuilder()\n .partial(Optional.ofNullable((Boolean) eventMetadata.get(\"partial\")).orElse(false))\n .turnComplete(\n Optional.ofNullable((Boolean) eventMetadata.get(\"turnComplete\")).orElse(false))\n .interrupted(\n Optional.ofNullable((Boolean) eventMetadata.get(\"interrupted\")).orElse(false))\n .branch(Optional.ofNullable((String) eventMetadata.get(\"branch\")))\n .groundingMetadata(groundingMetadata)\n .longRunningToolIds(\n longRunningToolIdsList != null ? new HashSet<>(longRunningToolIdsList) : null)\n .build();\n }\n return event;\n }\n\n /**\n * Converts a timestamp from a Map or String into an {@link Instant}.\n *\n * @param timestampObj map with \"seconds\"/\"nanos\" or an ISO string.\n * @return parsed {@link Instant}.\n */\n private static Instant convertToInstant(Object timestampObj) {\n if (timestampObj instanceof Map timestampMap) {\n return Instant.ofEpochSecond(\n ((Number) timestampMap.get(\"seconds\")).longValue(),\n ((Number) timestampMap.get(\"nanos\")).longValue());\n } else if (timestampObj != null) {\n return Instant.parse(timestampObj.toString());\n } else {\n throw new IllegalArgumentException(\"Timestamp not found in apiEvent\");\n }\n }\n\n /**\n * Converts a nested map into a {@link ConcurrentMap} of {@link ConcurrentMap}s.\n *\n * @return thread-safe nested map.\n */\n @SuppressWarnings(\"unchecked\")\n private static ConcurrentMap>\n asConcurrentMapOfConcurrentMaps(Object value) {\n return ((Map>) value)\n .entrySet().stream()\n .collect(\n ConcurrentHashMap::new,\n (map, entry) -> map.put(entry.getKey(), new ConcurrentHashMap<>(entry.getValue())),\n ConcurrentHashMap::putAll);\n }\n\n /** Regex for parsing full ReasoningEngine resource names. */\n private static final Pattern APP_NAME_PATTERN =\n Pattern.compile(\n \"^projects/([a-zA-Z0-9-_]+)/locations/([a-zA-Z0-9-_]+)/reasoningEngines/(\\\\d+)$\");\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/sessions/BaseSessionService.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\nimport com.google.adk.events.Event;\nimport com.google.adk.events.EventActions;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport io.reactivex.rxjava3.core.Completable;\nimport io.reactivex.rxjava3.core.Maybe;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.List;\nimport java.util.Objects;\nimport java.util.Optional;\nimport java.util.concurrent.ConcurrentMap;\nimport javax.annotation.Nullable;\n\n/**\n * Defines the contract for managing {@link Session}s and their associated {@link Event}s. Provides\n * methods for creating, retrieving, listing, and deleting sessions, as well as listing and\n * appending events to a session. Implementations of this interface handle the underlying storage\n * and retrieval logic.\n */\npublic interface BaseSessionService {\n\n /**\n * Creates a new session with the specified parameters.\n *\n * @param appName The name of the application associated with the session.\n * @param userId The identifier for the user associated with the session.\n * @param state An optional map representing the initial state of the session. Can be null or\n * empty.\n * @param sessionId An optional client-provided identifier for the session. If empty or null, the\n * service should generate a unique ID.\n * @return The newly created {@link Session} instance.\n * @throws SessionException if creation fails.\n */\n Single createSession(\n String appName,\n String userId,\n @Nullable ConcurrentMap state,\n @Nullable String sessionId);\n\n /**\n * Creates a new session with the specified application name and user ID, using a default state\n * (null) and allowing the service to generate a unique session ID.\n *\n *

This is a shortcut for {@link #createSession(String, String, Map, String)} with null state\n * and a null session ID.\n *\n * @param appName The name of the application associated with the session.\n * @param userId The identifier for the user associated with the session.\n * @return The newly created {@link Session} instance.\n * @throws SessionException if creation fails.\n */\n default Single createSession(String appName, String userId) {\n return createSession(appName, userId, null, null);\n }\n\n /**\n * Retrieves a specific session, optionally filtering the events included.\n *\n * @param appName The name of the application.\n * @param userId The identifier of the user.\n * @param sessionId The unique identifier of the session to retrieve.\n * @param config Optional configuration to filter the events returned within the session (e.g.,\n * limit number of recent events, filter by timestamp). If empty, default retrieval behavior\n * is used (potentially all events or a service-defined limit).\n * @return An {@link Optional} containing the {@link Session} if found, otherwise {@link\n * Optional#empty()}.\n * @throws SessionException for retrieval errors other than not found.\n */\n Maybe getSession(\n String appName, String userId, String sessionId, Optional config);\n\n /**\n * Lists sessions associated with a specific application and user.\n *\n *

The {@link Session} objects in the response typically contain only metadata (like ID,\n * creation time) and not the full event list or state to optimize performance.\n *\n * @param appName The name of the application.\n * @param userId The identifier of the user whose sessions are to be listed.\n * @return A {@link ListSessionsResponse} containing a list of matching sessions.\n * @throws SessionException if listing fails.\n */\n Single listSessions(String appName, String userId);\n\n /**\n * Deletes a specific session.\n *\n * @param appName The name of the application.\n * @param userId The identifier of the user.\n * @param sessionId The unique identifier of the session to delete.\n * @throws SessionNotFoundException if the session doesn't exist.\n * @throws SessionException for other deletion errors.\n */\n Completable deleteSession(String appName, String userId, String sessionId);\n\n /**\n * Lists the events within a specific session. Supports pagination via the response object.\n *\n * @param appName The name of the application.\n * @param userId The identifier of the user.\n * @param sessionId The unique identifier of the session whose events are to be listed.\n * @return A {@link ListEventsResponse} containing a list of events and an optional token for\n * retrieving the next page.\n * @throws SessionNotFoundException if the session doesn't exist.\n * @throws SessionException for other listing errors.\n */\n Single listEvents(String appName, String userId, String sessionId);\n\n /**\n * Closes a session. This is currently a placeholder and may involve finalizing session state or\n * performing cleanup actions in future implementations. The default implementation does nothing.\n *\n * @param session The session object to close.\n */\n default Completable closeSession(Session session) {\n // Default implementation does nothing.\n // TODO: Determine whether we want to finalize the session here.\n return Completable.complete();\n }\n\n /**\n * Appends an event to an in-memory session object and updates the session's state based on the\n * event's state delta, if applicable.\n *\n *

This method primarily modifies the passed {@code session} object in memory. Persisting these\n * changes typically requires a separate call to an update/save method provided by the specific\n * service implementation, or might happen implicitly depending on the implementation's design.\n *\n *

If the event is marked as partial (e.g., {@code event.isPartial() == true}), it is returned\n * directly without modifying the session state or event list. State delta keys starting with\n * {@link State#TEMP_PREFIX} are ignored during state updates.\n *\n * @param session The {@link Session} object to which the event should be appended (will be\n * mutated).\n * @param event The {@link Event} to append.\n * @return The appended {@link Event} instance (or the original event if it was partial).\n * @throws NullPointerException if session or event is null.\n */\n @CanIgnoreReturnValue\n default Single appendEvent(Session session, Event event) {\n Objects.requireNonNull(session, \"session cannot be null\");\n Objects.requireNonNull(event, \"event cannot be null\");\n\n // If the event indicates it's partial or incomplete, don't process it yet.\n if (event.partial().orElse(false)) {\n return Single.just(event);\n }\n\n EventActions actions = event.actions();\n if (actions != null) {\n ConcurrentMap stateDelta = actions.stateDelta();\n if (stateDelta != null && !stateDelta.isEmpty()) {\n ConcurrentMap sessionState = session.state();\n if (sessionState != null) {\n stateDelta.forEach(\n (key, value) -> {\n if (!key.startsWith(State.TEMP_PREFIX)) {\n sessionState.put(key, value);\n }\n });\n }\n }\n }\n\n List sessionEvents = session.events();\n if (sessionEvents != null) {\n sessionEvents.add(event);\n }\n\n return Single.just(event);\n }\n}\n"], ["/adk-java/dev/src/main/java/com/google/adk/web/AdkWebServer.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.web;\n\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.google.adk.JsonBaseModel;\nimport com.google.adk.agents.BaseAgent;\nimport com.google.adk.agents.LiveRequest;\nimport com.google.adk.agents.LiveRequestQueue;\nimport com.google.adk.agents.RunConfig;\nimport com.google.adk.agents.RunConfig.StreamingMode;\nimport com.google.adk.artifacts.BaseArtifactService;\nimport com.google.adk.artifacts.InMemoryArtifactService;\nimport com.google.adk.artifacts.ListArtifactsResponse;\nimport com.google.adk.events.Event;\nimport com.google.adk.runner.Runner;\nimport com.google.adk.sessions.BaseSessionService;\nimport com.google.adk.sessions.InMemorySessionService;\nimport com.google.adk.sessions.ListSessionsResponse;\nimport com.google.adk.sessions.Session;\nimport com.google.adk.web.config.AgentLoadingProperties;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Lists;\nimport com.google.genai.types.Blob;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.FunctionCall;\nimport com.google.genai.types.FunctionResponse;\nimport com.google.genai.types.Modality;\nimport com.google.genai.types.Part;\nimport io.opentelemetry.api.OpenTelemetry;\nimport io.opentelemetry.api.common.AttributeKey;\nimport io.opentelemetry.api.common.Attributes;\nimport io.opentelemetry.api.trace.SpanId;\nimport io.opentelemetry.sdk.OpenTelemetrySdk;\nimport io.opentelemetry.sdk.common.CompletableResultCode;\nimport io.opentelemetry.sdk.resources.Resource;\nimport io.opentelemetry.sdk.trace.SdkTracerProvider;\nimport io.opentelemetry.sdk.trace.data.SpanData;\nimport io.opentelemetry.sdk.trace.export.SimpleSpanProcessor;\nimport io.opentelemetry.sdk.trace.export.SpanExporter;\nimport io.reactivex.rxjava3.core.Flowable;\nimport io.reactivex.rxjava3.core.Maybe;\nimport io.reactivex.rxjava3.core.Single;\nimport io.reactivex.rxjava3.disposables.Disposable;\nimport io.reactivex.rxjava3.schedulers.Schedulers;\nimport java.io.IOException;\nimport java.net.URI;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.Optional;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.stream.Collectors;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.beans.factory.annotation.Qualifier;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.boot.context.properties.ConfigurationPropertiesScan;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.ComponentScan;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.http.MediaType;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.stereotype.Component;\nimport org.springframework.util.MultiValueMap;\nimport org.springframework.web.bind.annotation.DeleteMapping;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.PostMapping;\nimport org.springframework.web.bind.annotation.RequestBody;\nimport org.springframework.web.bind.annotation.RequestParam;\nimport org.springframework.web.bind.annotation.RestController;\nimport org.springframework.web.server.ResponseStatusException;\nimport org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;\nimport org.springframework.web.servlet.config.annotation.ViewControllerRegistry;\nimport org.springframework.web.servlet.config.annotation.WebMvcConfigurer;\nimport org.springframework.web.servlet.mvc.method.annotation.SseEmitter;\nimport org.springframework.web.socket.CloseStatus;\nimport org.springframework.web.socket.TextMessage;\nimport org.springframework.web.socket.WebSocketSession;\nimport org.springframework.web.socket.config.annotation.EnableWebSocket;\nimport org.springframework.web.socket.config.annotation.WebSocketConfigurer;\nimport org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;\nimport org.springframework.web.socket.handler.TextWebSocketHandler;\nimport org.springframework.web.util.UriComponentsBuilder;\n\n/**\n * Single-file Spring Boot application for the Agent Server. Combines configuration, DTOs, and\n * controller logic.\n */\n@SpringBootApplication\n@ConfigurationPropertiesScan\n@ComponentScan(basePackages = {\"com.google.adk.web\", \"com.google.adk.web.config\"})\npublic class AdkWebServer implements WebMvcConfigurer {\n\n private static final Logger log = LoggerFactory.getLogger(AdkWebServer.class);\n\n @Value(\"${adk.web.ui.dir:#{null}}\")\n private String webUiDir;\n\n @Bean\n public BaseSessionService sessionService() {\n // TODO: Add logic to select service based on config (e.g., DB URL)\n log.info(\"Using InMemorySessionService\");\n return new InMemorySessionService();\n }\n\n /**\n * Provides the singleton instance of the ArtifactService (InMemory). TODO: configure this based\n * on config (e.g., DB URL)\n *\n * @return An instance of BaseArtifactService (currently InMemoryArtifactService).\n */\n @Bean\n public BaseArtifactService artifactService() {\n log.info(\"Using InMemoryArtifactService\");\n return new InMemoryArtifactService();\n }\n\n @Bean(\"loadedAgentRegistry\")\n public Map loadedAgentRegistry(\n AgentCompilerLoader loader, AgentLoadingProperties props) {\n if (props.getSourceDir() == null || props.getSourceDir().isEmpty()) {\n log.info(\"adk.agents.source-dir not set. Initializing with an empty agent registry.\");\n return Collections.emptyMap();\n }\n try {\n Map agents = loader.loadAgents();\n log.info(\"Loaded {} dynamic agent(s): {}\", agents.size(), agents.keySet());\n return agents;\n } catch (IOException e) {\n log.error(\"Failed to load dynamic agents\", e);\n return Collections.emptyMap();\n }\n }\n\n @Bean\n public ObjectMapper objectMapper() {\n return JsonBaseModel.getMapper();\n }\n\n /** Service for creating and caching Runner instances. */\n @Component\n public static class RunnerService {\n private static final Logger log = LoggerFactory.getLogger(RunnerService.class);\n\n private final Map agentRegistry;\n private final BaseArtifactService artifactService;\n private final BaseSessionService sessionService;\n private final Map runnerCache = new ConcurrentHashMap<>();\n\n @Autowired\n public RunnerService(\n @Qualifier(\"loadedAgentRegistry\") Map agentRegistry,\n BaseArtifactService artifactService,\n BaseSessionService sessionService) {\n this.agentRegistry = agentRegistry;\n this.artifactService = artifactService;\n this.sessionService = sessionService;\n }\n\n /**\n * Gets the Runner instance for a given application name. Handles potential agent engine ID\n * overrides.\n *\n * @param appName The application name requested by the user.\n * @return A configured Runner instance.\n */\n public Runner getRunner(String appName) {\n return runnerCache.computeIfAbsent(\n appName,\n key -> {\n BaseAgent agent = agentRegistry.get(key);\n if (agent == null) {\n log.error(\n \"Agent/App named '{}' not found in registry. Available apps: {}\",\n key,\n agentRegistry.keySet());\n throw new ResponseStatusException(\n HttpStatus.NOT_FOUND, \"Agent/App not found: \" + key);\n }\n log.info(\n \"RunnerService: Creating Runner for appName: {}, using agent\" + \" definition: {}\",\n appName,\n agent.name());\n return new Runner(agent, appName, this.artifactService, this.sessionService);\n });\n }\n }\n\n /** Configuration class for OpenTelemetry, setting up the tracer provider and span exporter. */\n @Configuration\n public static class OpenTelemetryConfig {\n private static final Logger otelLog = LoggerFactory.getLogger(OpenTelemetryConfig.class);\n\n @Bean\n public ApiServerSpanExporter apiServerSpanExporter() {\n return new ApiServerSpanExporter();\n }\n\n @Bean(destroyMethod = \"shutdown\")\n public SdkTracerProvider sdkTracerProvider(ApiServerSpanExporter apiServerSpanExporter) {\n otelLog.debug(\"Configuring SdkTracerProvider with ApiServerSpanExporter.\");\n Resource resource =\n Resource.getDefault()\n .merge(\n Resource.create(\n Attributes.of(AttributeKey.stringKey(\"service.name\"), \"adk-web-server\")));\n\n return SdkTracerProvider.builder()\n .addSpanProcessor(SimpleSpanProcessor.create(apiServerSpanExporter))\n .setResource(resource)\n .build();\n }\n\n @Bean\n public OpenTelemetry openTelemetrySdk(SdkTracerProvider sdkTracerProvider) {\n otelLog.debug(\"Configuring OpenTelemetrySdk and registering globally.\");\n OpenTelemetrySdk otelSdk =\n OpenTelemetrySdk.builder().setTracerProvider(sdkTracerProvider).buildAndRegisterGlobal();\n\n Runtime.getRuntime().addShutdownHook(new Thread(otelSdk::close));\n return otelSdk;\n }\n }\n\n /**\n * A custom SpanExporter that stores relevant span data. It handles two types of trace data\n * storage: 1. Event-ID based: Stores attributes of specific spans (call_llm, send_data,\n * tool_response) keyed by `gcp.vertex.agent.event_id`. This is used for debugging individual\n * events. 2. Session-ID based: Stores all exported spans and maintains a mapping from\n * `session_id` (extracted from `call_llm` spans) to a list of `trace_id`s. This is used for\n * retrieving all spans related to a session.\n */\n public static class ApiServerSpanExporter implements SpanExporter {\n private static final Logger exporterLog = LoggerFactory.getLogger(ApiServerSpanExporter.class);\n\n private final Map> eventIdTraceStorage = new ConcurrentHashMap<>();\n\n // Session ID -> Trace IDs -> Trace Object\n private final Map> sessionToTraceIdsMap = new ConcurrentHashMap<>();\n\n private final List allExportedSpans = Collections.synchronizedList(new ArrayList<>());\n\n public ApiServerSpanExporter() {}\n\n public Map getEventTraceAttributes(String eventId) {\n return this.eventIdTraceStorage.get(eventId);\n }\n\n public Map> getSessionToTraceIdsMap() {\n return this.sessionToTraceIdsMap;\n }\n\n public List getAllExportedSpans() {\n return this.allExportedSpans;\n }\n\n @Override\n public CompletableResultCode export(Collection spans) {\n exporterLog.debug(\"ApiServerSpanExporter received {} spans to export.\", spans.size());\n List currentBatch = new ArrayList<>(spans);\n allExportedSpans.addAll(currentBatch);\n\n for (SpanData span : currentBatch) {\n String spanName = span.getName();\n if (\"call_llm\".equals(spanName)\n || \"send_data\".equals(spanName)\n || (spanName != null && spanName.startsWith(\"tool_response\"))) {\n String eventId =\n span.getAttributes().get(AttributeKey.stringKey(\"gcp.vertex.agent.event_id\"));\n if (eventId != null && !eventId.isEmpty()) {\n Map attributesMap = new HashMap<>();\n span.getAttributes().forEach((key, value) -> attributesMap.put(key.getKey(), value));\n attributesMap.put(\"trace_id\", span.getSpanContext().getTraceId());\n attributesMap.put(\"span_id\", span.getSpanContext().getSpanId());\n attributesMap.putIfAbsent(\"gcp.vertex.agent.event_id\", eventId);\n exporterLog.debug(\"Storing event-based trace attributes for event_id: {}\", eventId);\n this.eventIdTraceStorage.put(eventId, attributesMap); // Use internal storage\n } else {\n exporterLog.trace(\n \"Span {} for event-based trace did not have 'gcp.vertex.agent.event_id'\"\n + \" attribute or it was empty.\",\n spanName);\n }\n }\n\n if (\"call_llm\".equals(spanName)) {\n String sessionId =\n span.getAttributes().get(AttributeKey.stringKey(\"gcp.vertex.agent.session_id\"));\n if (sessionId != null && !sessionId.isEmpty()) {\n String traceId = span.getSpanContext().getTraceId();\n sessionToTraceIdsMap\n .computeIfAbsent(sessionId, k -> Collections.synchronizedList(new ArrayList<>()))\n .add(traceId);\n exporterLog.trace(\n \"Associated trace_id {} with session_id {} for session tracing\",\n traceId,\n sessionId);\n } else {\n exporterLog.trace(\n \"Span {} for session trace did not have 'gcp.vertex.agent.session_id' attribute.\",\n spanName);\n }\n }\n }\n return CompletableResultCode.ofSuccess();\n }\n\n @Override\n public CompletableResultCode flush() {\n return CompletableResultCode.ofSuccess();\n }\n\n @Override\n public CompletableResultCode shutdown() {\n exporterLog.debug(\"Shutting down ApiServerSpanExporter.\");\n // no need to clear storage on shutdown, as everything is currently stored in memory.\n return CompletableResultCode.ofSuccess();\n }\n }\n\n /**\n * Data Transfer Object (DTO) for POST /run and POST /run-sse requests. Contains information\n * needed to execute an agent run.\n */\n public static class AgentRunRequest {\n @JsonProperty(\"appName\")\n public String appName;\n\n @JsonProperty(\"userId\")\n public String userId;\n\n @JsonProperty(\"sessionId\")\n public String sessionId;\n\n @JsonProperty(\"newMessage\")\n public Content newMessage;\n\n @JsonProperty(\"streaming\")\n public boolean streaming = false;\n\n public AgentRunRequest() {}\n\n public String getAppName() {\n return appName;\n }\n\n public String getUserId() {\n return userId;\n }\n\n public String getSessionId() {\n return sessionId;\n }\n\n public Content getNewMessage() {\n return newMessage;\n }\n\n public boolean getStreaming() {\n return streaming;\n }\n }\n\n /**\n * DTO for POST /apps/{appName}/eval_sets/{evalSetId}/add-session requests. Contains information\n * to associate a session with an evaluation set.\n */\n public static class AddSessionToEvalSetRequest {\n @JsonProperty(\"evalId\")\n public String evalId;\n\n @JsonProperty(\"sessionId\")\n public String sessionId;\n\n @JsonProperty(\"userId\")\n public String userId;\n\n public AddSessionToEvalSetRequest() {}\n\n public String getEvalId() {\n return evalId;\n }\n\n public String getSessionId() {\n return sessionId;\n }\n\n public String getUserId() {\n return userId;\n }\n }\n\n /**\n * DTO for POST /apps/{appName}/eval_sets/{evalSetId}/run-eval requests. Contains information for\n * running evaluations.\n */\n public static class RunEvalRequest {\n @JsonProperty(\"evalIds\")\n public List evalIds;\n\n @JsonProperty(\"evalMetrics\")\n public List evalMetrics;\n\n public RunEvalRequest() {}\n\n public List getEvalIds() {\n return evalIds;\n }\n\n public List getEvalMetrics() {\n return evalMetrics;\n }\n }\n\n /**\n * DTO for the response of POST /apps/{appName}/eval_sets/{evalSetId}/run-eval. Contains the\n * results of an evaluation run.\n */\n public static class RunEvalResult extends JsonBaseModel {\n @JsonProperty(\"appName\")\n public String appName;\n\n @JsonProperty(\"evalSetId\")\n public String evalSetId;\n\n @JsonProperty(\"evalId\")\n public String evalId;\n\n @JsonProperty(\"finalEvalStatus\")\n public String finalEvalStatus;\n\n @JsonProperty(\"evalMetricResults\")\n public List> evalMetricResults;\n\n @JsonProperty(\"sessionId\")\n public String sessionId;\n\n /**\n * Constructs a RunEvalResult.\n *\n * @param appName The application name.\n * @param evalSetId The evaluation set ID.\n * @param evalId The evaluation ID.\n * @param finalEvalStatus The final status of the evaluation.\n * @param evalMetricResults The results for each metric.\n * @param sessionId The session ID associated with the evaluation.\n */\n public RunEvalResult(\n String appName,\n String evalSetId,\n String evalId,\n String finalEvalStatus,\n List> evalMetricResults,\n String sessionId) {\n this.appName = appName;\n this.evalSetId = evalSetId;\n this.evalId = evalId;\n this.finalEvalStatus = finalEvalStatus;\n this.evalMetricResults = evalMetricResults;\n this.sessionId = sessionId;\n }\n\n public RunEvalResult() {}\n }\n\n /**\n * DTO for the response of GET\n * /apps/{appName}/users/{userId}/sessions/{sessionId}/events/{eventId}/graph. Contains the graph\n * representation (e.g., DOT source).\n */\n public static class GraphResponse {\n @JsonProperty(\"dotSrc\")\n public String dotSrc;\n\n /**\n * Constructs a GraphResponse.\n *\n * @param dotSrc The graph source string (e.g., in DOT format).\n */\n public GraphResponse(String dotSrc) {\n this.dotSrc = dotSrc;\n }\n\n public GraphResponse() {}\n\n public String getDotSrc() {\n return dotSrc;\n }\n }\n\n /**\n * Configures resource handlers for serving static content (like the Dev UI). Maps requests\n * starting with \"/dev-ui/\" to the directory specified by the 'adk.web.ui.dir' system property.\n */\n @Override\n public void addResourceHandlers(ResourceHandlerRegistry registry) {\n if (webUiDir != null && !webUiDir.isEmpty()) {\n // Ensure the path uses forward slashes and ends with a slash\n String location = webUiDir.replace(\"\\\\\", \"/\");\n if (!location.startsWith(\"file:\")) {\n location = \"file:\" + location; // Ensure file: prefix\n }\n if (!location.endsWith(\"/\")) {\n location += \"/\";\n }\n log.debug(\"Mapping URL path /** to static resources at location: {}\", location);\n registry\n .addResourceHandler(\"/**\")\n .addResourceLocations(location)\n .setCachePeriod(0)\n .resourceChain(true);\n\n } else {\n log.debug(\n \"System property 'adk.web.ui.dir' or config 'adk.web.ui.dir' is not set. Mapping URL path\"\n + \" /** to classpath:/browser/\");\n registry\n .addResourceHandler(\"/**\")\n .addResourceLocations(\"classpath:/browser/\")\n .setCachePeriod(0)\n .resourceChain(true);\n }\n }\n\n /**\n * Configures simple automated controllers: - Redirects the root path \"/\" to \"/dev-ui\". - Forwards\n * requests to \"/dev-ui\" to \"/dev-ui/index.html\" so the ResourceHandler serves it.\n */\n @Override\n public void addViewControllers(ViewControllerRegistry registry) {\n registry.addRedirectViewController(\"/\", \"/dev-ui\");\n registry.addViewController(\"/dev-ui\").setViewName(\"forward:/index.html\");\n registry.addViewController(\"/dev-ui/\").setViewName(\"forward:/index.html\");\n }\n\n /** Spring Boot REST Controller handling agent-related API endpoints. */\n @RestController\n public static class AgentController {\n\n private static final Logger log = LoggerFactory.getLogger(AgentController.class);\n\n private static final String EVAL_SESSION_ID_PREFIX = \"ADK_EVAL_\";\n\n private final BaseSessionService sessionService;\n private final BaseArtifactService artifactService;\n private final Map agentRegistry;\n private final ApiServerSpanExporter apiServerSpanExporter;\n private final RunnerService runnerService;\n private final ExecutorService sseExecutor = Executors.newCachedThreadPool();\n\n /**\n * Constructs the AgentController.\n *\n * @param sessionService The service for managing sessions.\n * @param artifactService The service for managing artifacts.\n * @param agentRegistry The registry of loaded agents.\n * @param apiServerSpanExporter The exporter holding all trace data.\n * @param runnerService The service for obtaining Runner instances.\n */\n @Autowired\n public AgentController(\n BaseSessionService sessionService,\n BaseArtifactService artifactService,\n @Qualifier(\"loadedAgentRegistry\") Map agentRegistry,\n ApiServerSpanExporter apiServerSpanExporter,\n RunnerService runnerService) {\n this.sessionService = sessionService;\n this.artifactService = artifactService;\n this.agentRegistry = agentRegistry;\n this.apiServerSpanExporter = apiServerSpanExporter;\n this.runnerService = runnerService;\n log.info(\n \"AgentController initialized with {} dynamic agents: {}\",\n agentRegistry.size(),\n agentRegistry.keySet());\n if (agentRegistry.isEmpty()) {\n log.warn(\n \"Agent registry is empty. Check 'adk.agents.source-dir' property and compilation\"\n + \" logs.\");\n }\n }\n\n /**\n * Finds a session by its identifiers or throws a ResponseStatusException if not found or if\n * there's an app/user mismatch.\n *\n * @param appName The application name.\n * @param userId The user ID.\n * @param sessionId The session ID.\n * @return The found Session object.\n * @throws ResponseStatusException with HttpStatus.NOT_FOUND if the session doesn't exist or\n * belongs to a different app/user.\n */\n private Session findSessionOrThrow(String appName, String userId, String sessionId) {\n Maybe maybeSession =\n sessionService.getSession(appName, userId, sessionId, Optional.empty());\n\n Session session = maybeSession.blockingGet();\n\n if (session == null) {\n log.warn(\n \"Session not found for appName={}, userId={}, sessionId={}\",\n appName,\n userId,\n sessionId);\n throw new ResponseStatusException(\n HttpStatus.NOT_FOUND,\n String.format(\n \"Session not found: appName=%s, userId=%s, sessionId=%s\",\n appName, userId, sessionId));\n }\n\n if (!Objects.equals(session.appName(), appName)\n || !Objects.equals(session.userId(), userId)) {\n log.warn(\n \"Session ID {} found but appName/userId mismatch (Expected: {}/{}, Found: {}/{}) -\"\n + \" Treating as not found.\",\n sessionId,\n appName,\n userId,\n session.appName(),\n session.userId());\n\n throw new ResponseStatusException(\n HttpStatus.NOT_FOUND, \"Session found but belongs to a different app/user.\");\n }\n log.debug(\"Found session: {}\", sessionId);\n return session;\n }\n\n /**\n * Lists available applications. Currently returns only the configured root agent's name.\n *\n * @return A list containing the root agent's name.\n */\n @GetMapping(\"/list-apps\")\n public List listApps() {\n log.info(\"Listing apps from dynamic registry. Found: {}\", agentRegistry.keySet());\n List appNames = new ArrayList<>(agentRegistry.keySet());\n Collections.sort(appNames);\n return appNames;\n }\n\n /**\n * Endpoint for retrieving trace information stored by the ApiServerSpanExporter, based on event\n * ID.\n *\n * @param eventId The ID of the event to trace (expected to be gcp.vertex.agent.event_id).\n * @return A ResponseEntity containing the trace data or NOT_FOUND.\n */\n @GetMapping(\"/debug/trace/{eventId}\")\n public ResponseEntity getTraceDict(@PathVariable String eventId) {\n log.info(\"Request received for GET /debug/trace/{}\", eventId);\n Map traceData = this.apiServerSpanExporter.getEventTraceAttributes(eventId);\n if (traceData == null) {\n log.warn(\"Trace not found for eventId: {}\", eventId);\n return ResponseEntity.status(HttpStatus.NOT_FOUND)\n .body(Collections.singletonMap(\"message\", \"Trace not found for eventId: \" + eventId));\n }\n log.info(\"Returning trace data for eventId: {}\", eventId);\n return ResponseEntity.ok(traceData);\n }\n\n /**\n * Retrieves trace spans for a given session ID.\n *\n * @param sessionId The session ID.\n * @return A ResponseEntity containing a list of span data maps for the session, or an empty\n * list.\n */\n @GetMapping(\"/debug/trace/session/{sessionId}\")\n public ResponseEntity getSessionTrace(@PathVariable String sessionId) {\n log.info(\"Request received for GET /debug/trace/session/{}\", sessionId);\n\n List traceIdsForSession =\n this.apiServerSpanExporter.getSessionToTraceIdsMap().get(sessionId);\n\n if (traceIdsForSession == null || traceIdsForSession.isEmpty()) {\n log.warn(\"No trace IDs found for session ID: {}\", sessionId);\n return ResponseEntity.ok(Collections.emptyList());\n }\n\n // Iterate over a snapshot of all spans to avoid concurrent modification issues\n // if the exporter is actively adding spans.\n List allSpansSnapshot =\n new ArrayList<>(this.apiServerSpanExporter.getAllExportedSpans());\n\n if (allSpansSnapshot.isEmpty()) {\n log.warn(\"No spans have been exported yet overall.\");\n return ResponseEntity.ok(Collections.emptyList());\n }\n\n Set relevantTraceIds = new HashSet<>(traceIdsForSession);\n List> resultSpans = new ArrayList<>();\n\n for (SpanData span : allSpansSnapshot) {\n if (relevantTraceIds.contains(span.getSpanContext().getTraceId())) {\n Map spanMap = new HashMap<>();\n spanMap.put(\"name\", span.getName());\n spanMap.put(\"span_id\", span.getSpanContext().getSpanId());\n spanMap.put(\"trace_id\", span.getSpanContext().getTraceId());\n spanMap.put(\"start_time\", span.getStartEpochNanos());\n spanMap.put(\"end_time\", span.getEndEpochNanos());\n\n Map attributesMap = new HashMap<>();\n span.getAttributes().forEach((key, value) -> attributesMap.put(key.getKey(), value));\n spanMap.put(\"attributes\", attributesMap);\n\n String parentSpanId = span.getParentSpanId();\n if (SpanId.isValid(parentSpanId)) {\n spanMap.put(\"parent_span_id\", parentSpanId);\n } else {\n spanMap.put(\"parent_span_id\", null);\n }\n resultSpans.add(spanMap);\n }\n }\n\n log.info(\"Returning {} spans for session ID: {}\", resultSpans.size(), sessionId);\n return ResponseEntity.ok(resultSpans);\n }\n\n /**\n * Retrieves a specific session by its ID.\n *\n * @param appName The application name.\n * @param userId The user ID.\n * @param sessionId The session ID.\n * @return The requested Session object.\n * @throws ResponseStatusException if the session is not found.\n */\n @GetMapping(\"/apps/{appName}/users/{userId}/sessions/{sessionId}\")\n public Session getSession(\n @PathVariable String appName, @PathVariable String userId, @PathVariable String sessionId) {\n log.info(\n \"Request received for GET /apps/{}/users/{}/sessions/{}\", appName, userId, sessionId);\n return findSessionOrThrow(appName, userId, sessionId);\n }\n\n /**\n * Lists all non-evaluation sessions for a given app and user.\n *\n * @param appName The name of the application.\n * @param userId The ID of the user.\n * @return A list of sessions, excluding those used for evaluation.\n */\n @GetMapping(\"/apps/{appName}/users/{userId}/sessions\")\n public List listSessions(@PathVariable String appName, @PathVariable String userId) {\n log.info(\"Request received for GET /apps/{}/users/{}/sessions\", appName, userId);\n\n Single sessionsResponseSingle =\n sessionService.listSessions(appName, userId);\n\n ListSessionsResponse response = sessionsResponseSingle.blockingGet();\n if (response == null || response.sessions() == null) {\n log.warn(\n \"Received null response or null sessions list for listSessions({}, {})\",\n appName,\n userId);\n return Collections.emptyList();\n }\n\n List filteredSessions =\n response.sessions().stream()\n .filter(s -> !s.id().startsWith(EVAL_SESSION_ID_PREFIX))\n .collect(Collectors.toList());\n log.info(\n \"Found {} non-evaluation sessions for app={}, user={}\",\n filteredSessions.size(),\n appName,\n userId);\n return filteredSessions;\n }\n\n /**\n * Creates a new session with a specific ID provided by the client.\n *\n * @param appName The application name.\n * @param userId The user ID.\n * @param sessionId The desired session ID.\n * @param state Optional initial state for the session.\n * @return The newly created Session object.\n * @throws ResponseStatusException if a session with the given ID already exists (BAD_REQUEST)\n * or if creation fails (INTERNAL_SERVER_ERROR).\n */\n @PostMapping(\"/apps/{appName}/users/{userId}/sessions/{sessionId}\")\n public Session createSessionWithId(\n @PathVariable String appName,\n @PathVariable String userId,\n @PathVariable String sessionId,\n @RequestBody(required = false) Map state) {\n log.info(\n \"Request received for POST /apps/{}/users/{}/sessions/{} with state: {}\",\n appName,\n userId,\n sessionId,\n state);\n\n try {\n findSessionOrThrow(appName, userId, sessionId);\n\n log.warn(\"Attempted to create session with existing ID: {}\", sessionId);\n throw new ResponseStatusException(\n HttpStatus.BAD_REQUEST, \"Session already exists: \" + sessionId);\n } catch (ResponseStatusException e) {\n\n if (e.getStatusCode() != HttpStatus.NOT_FOUND) {\n throw e;\n }\n\n log.info(\"Session {} not found, proceeding with creation.\", sessionId);\n }\n\n Map initialState = (state != null) ? state : Collections.emptyMap();\n try {\n Session createdSession =\n sessionService\n .createSession(appName, userId, new ConcurrentHashMap<>(initialState), sessionId)\n .blockingGet();\n\n if (createdSession == null) {\n\n log.error(\n \"Session creation call completed without error but returned null session for {}\",\n sessionId);\n throw new ResponseStatusException(\n HttpStatus.INTERNAL_SERVER_ERROR, \"Failed to create session (null result)\");\n }\n log.info(\"Session created successfully with id: {}\", createdSession.id());\n return createdSession;\n } catch (Exception e) {\n log.error(\"Error creating session with id {}\", sessionId, e);\n\n throw new ResponseStatusException(\n HttpStatus.INTERNAL_SERVER_ERROR, \"Error creating session\", e);\n }\n }\n\n /**\n * Creates a new session where the ID is generated by the service.\n *\n * @param appName The application name.\n * @param userId The user ID.\n * @param state Optional initial state for the session.\n * @return The newly created Session object.\n * @throws ResponseStatusException if creation fails (INTERNAL_SERVER_ERROR).\n */\n @PostMapping(\"/apps/{appName}/users/{userId}/sessions\")\n public Session createSession(\n @PathVariable String appName,\n @PathVariable String userId,\n @RequestBody(required = false) Map state) {\n\n log.info(\n \"Request received for POST /apps/{}/users/{}/sessions (service generates ID) with state:\"\n + \" {}\",\n appName,\n userId,\n state);\n\n Map initialState = (state != null) ? state : Collections.emptyMap();\n try {\n\n Session createdSession =\n sessionService\n .createSession(appName, userId, new ConcurrentHashMap<>(initialState), null)\n .blockingGet();\n\n if (createdSession == null) {\n log.error(\n \"Session creation call completed without error but returned null session for user {}\",\n userId);\n throw new ResponseStatusException(\n HttpStatus.INTERNAL_SERVER_ERROR, \"Failed to create session (null result)\");\n }\n log.info(\"Session created successfully with generated id: {}\", createdSession.id());\n return createdSession;\n } catch (Exception e) {\n log.error(\"Error creating session for user {}\", userId, e);\n throw new ResponseStatusException(\n HttpStatus.INTERNAL_SERVER_ERROR, \"Error creating session\", e);\n }\n }\n\n /**\n * Deletes a specific session.\n *\n * @param appName The application name.\n * @param userId The user ID.\n * @param sessionId The session ID to delete.\n * @return A ResponseEntity with status NO_CONTENT on success.\n * @throws ResponseStatusException if deletion fails (INTERNAL_SERVER_ERROR).\n */\n @DeleteMapping(\"/apps/{appName}/users/{userId}/sessions/{sessionId}\")\n public ResponseEntity deleteSession(\n @PathVariable String appName, @PathVariable String userId, @PathVariable String sessionId) {\n log.info(\n \"Request received for DELETE /apps/{}/users/{}/sessions/{}\", appName, userId, sessionId);\n try {\n\n sessionService.deleteSession(appName, userId, sessionId).blockingAwait();\n log.info(\"Session deleted successfully: {}\", sessionId);\n return ResponseEntity.noContent().build();\n } catch (Exception e) {\n\n log.error(\"Error deleting session {}\", sessionId, e);\n\n throw new ResponseStatusException(\n HttpStatus.INTERNAL_SERVER_ERROR, \"Error deleting session\", e);\n }\n }\n\n /**\n * Loads the latest or a specific version of an artifact associated with a session.\n *\n * @param appName The application name.\n * @param userId The user ID.\n * @param sessionId The session ID.\n * @param artifactName The name of the artifact.\n * @param version Optional specific version number. If null, loads the latest.\n * @return The artifact content as a Part object.\n * @throws ResponseStatusException if the artifact is not found (NOT_FOUND).\n */\n @GetMapping(\"/apps/{appName}/users/{userId}/sessions/{sessionId}/artifacts/{artifactName}\")\n public Part loadArtifact(\n @PathVariable String appName,\n @PathVariable String userId,\n @PathVariable String sessionId,\n @PathVariable String artifactName,\n @RequestParam(required = false) Integer version) {\n String versionStr = (version == null) ? \"latest\" : String.valueOf(version);\n log.info(\n \"Request received to load artifact: app={}, user={}, session={}, artifact={}, version={}\",\n appName,\n userId,\n sessionId,\n artifactName,\n versionStr);\n\n Maybe artifactMaybe =\n artifactService.loadArtifact(\n appName, userId, sessionId, artifactName, Optional.ofNullable(version));\n\n Part artifact = artifactMaybe.blockingGet();\n\n if (artifact == null) {\n log.warn(\n \"Artifact not found: app={}, user={}, session={}, artifact={}, version={}\",\n appName,\n userId,\n sessionId,\n artifactName,\n versionStr);\n throw new ResponseStatusException(HttpStatus.NOT_FOUND, \"Artifact not found\");\n }\n log.debug(\"Artifact {} version {} loaded successfully.\", artifactName, versionStr);\n return artifact;\n }\n\n /**\n * Loads a specific version of an artifact.\n *\n * @param appName The application name.\n * @param userId The user ID.\n * @param sessionId The session ID.\n * @param artifactName The name of the artifact.\n * @param versionId The specific version number.\n * @return The artifact content as a Part object.\n * @throws ResponseStatusException if the artifact version is not found (NOT_FOUND).\n */\n @GetMapping(\n \"/apps/{appName}/users/{userId}/sessions/{sessionId}/artifacts/{artifactName}/versions/{versionId}\")\n public Part loadArtifactVersion(\n @PathVariable String appName,\n @PathVariable String userId,\n @PathVariable String sessionId,\n @PathVariable String artifactName,\n @PathVariable int versionId) {\n log.info(\n \"Request received to load artifact version: app={}, user={}, session={}, artifact={},\"\n + \" version={}\",\n appName,\n userId,\n sessionId,\n artifactName,\n versionId);\n\n Maybe artifactMaybe =\n artifactService.loadArtifact(\n appName, userId, sessionId, artifactName, Optional.of(versionId));\n\n Part artifact = artifactMaybe.blockingGet();\n\n if (artifact == null) {\n log.warn(\n \"Artifact version not found: app={}, user={}, session={}, artifact={}, version={}\",\n appName,\n userId,\n sessionId,\n artifactName,\n versionId);\n throw new ResponseStatusException(HttpStatus.NOT_FOUND, \"Artifact version not found\");\n }\n log.debug(\"Artifact {} version {} loaded successfully.\", artifactName, versionId);\n return artifact;\n }\n\n /**\n * Lists the names of all artifacts associated with a session.\n *\n * @param appName The application name.\n * @param userId The user ID.\n * @param sessionId The session ID.\n * @return A list of artifact names.\n */\n @GetMapping(\"/apps/{appName}/users/{userId}/sessions/{sessionId}/artifacts\")\n public List listArtifactNames(\n @PathVariable String appName, @PathVariable String userId, @PathVariable String sessionId) {\n log.info(\n \"Request received to list artifact names for app={}, user={}, session={}\",\n appName,\n userId,\n sessionId);\n\n Single responseSingle =\n artifactService.listArtifactKeys(appName, userId, sessionId);\n\n ListArtifactsResponse response = responseSingle.blockingGet();\n List filenames =\n (response != null && response.filenames() != null)\n ? response.filenames()\n : Collections.emptyList();\n log.info(\"Found {} artifact names for session {}\", filenames.size(), sessionId);\n return filenames;\n }\n\n /**\n * Lists the available versions for a specific artifact.\n *\n * @param appName The application name.\n * @param userId The user ID.\n * @param sessionId The session ID.\n * @param artifactName The name of the artifact.\n * @return A list of version numbers (integers).\n */\n @GetMapping(\n \"/apps/{appName}/users/{userId}/sessions/{sessionId}/artifacts/{artifactName}/versions\")\n public List listArtifactVersions(\n @PathVariable String appName,\n @PathVariable String userId,\n @PathVariable String sessionId,\n @PathVariable String artifactName) {\n log.info(\n \"Request received to list versions for artifact: app={}, user={}, session={},\"\n + \" artifact={}\",\n appName,\n userId,\n sessionId,\n artifactName);\n\n Single> versionsSingle =\n artifactService.listVersions(appName, userId, sessionId, artifactName);\n ImmutableList versions = versionsSingle.blockingGet();\n log.info(\n \"Found {} versions for artifact {}\",\n versions != null ? versions.size() : 0,\n artifactName);\n return versions != null ? versions : Collections.emptyList();\n }\n\n /**\n * Deletes an artifact and all its versions.\n *\n * @param appName The application name.\n * @param userId The user ID.\n * @param sessionId The session ID.\n * @param artifactName The name of the artifact to delete.\n * @return A ResponseEntity with status NO_CONTENT on success.\n * @throws ResponseStatusException if deletion fails (INTERNAL_SERVER_ERROR).\n */\n @DeleteMapping(\"/apps/{appName}/users/{userId}/sessions/{sessionId}/artifacts/{artifactName}\")\n public ResponseEntity deleteArtifact(\n @PathVariable String appName,\n @PathVariable String userId,\n @PathVariable String sessionId,\n @PathVariable String artifactName) {\n log.info(\n \"Request received to delete artifact: app={}, user={}, session={}, artifact={}\",\n appName,\n userId,\n sessionId,\n artifactName);\n\n try {\n\n artifactService.deleteArtifact(appName, userId, sessionId, artifactName);\n log.info(\"Artifact deleted successfully: {}\", artifactName);\n return ResponseEntity.noContent().build();\n } catch (Exception e) {\n log.error(\"Error deleting artifact {}\", artifactName, e);\n\n throw new ResponseStatusException(\n HttpStatus.INTERNAL_SERVER_ERROR, \"Error deleting artifact\", e);\n }\n }\n\n /**\n * Executes a non-streaming agent run for a given session and message.\n *\n * @param request The AgentRunRequest containing run details.\n * @return A list of events generated during the run.\n * @throws ResponseStatusException if the session is not found or the run fails.\n */\n @PostMapping(\"/run\")\n public List agentRun(@RequestBody AgentRunRequest request) {\n if (request.appName == null || request.appName.trim().isEmpty()) {\n log.warn(\"appName cannot be null or empty in POST /run request.\");\n throw new ResponseStatusException(\n HttpStatus.BAD_REQUEST, \"appName cannot be null or empty\");\n }\n if (request.sessionId == null || request.sessionId.trim().isEmpty()) {\n log.warn(\"sessionId cannot be null or empty in POST /run request.\");\n throw new ResponseStatusException(\n HttpStatus.BAD_REQUEST, \"sessionId cannot be null or empty\");\n }\n log.info(\"Request received for POST /run for session: {}\", request.sessionId);\n\n Runner runner = this.runnerService.getRunner(request.appName);\n try {\n\n RunConfig runConfig = RunConfig.builder().setStreamingMode(StreamingMode.NONE).build();\n Flowable eventStream =\n runner.runAsync(request.userId, request.sessionId, request.newMessage, runConfig);\n\n List events = Lists.newArrayList(eventStream.blockingIterable());\n log.info(\"Agent run for session {} generated {} events.\", request.sessionId, events.size());\n return events;\n } catch (Exception e) {\n log.error(\"Error during agent run for session {}\", request.sessionId, e);\n throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, \"Agent run failed\", e);\n }\n }\n\n /**\n * Executes an agent run and streams the resulting events using Server-Sent Events (SSE).\n *\n * @param request The AgentRunRequest containing run details.\n * @return A Flux that will stream events to the client.\n */\n @PostMapping(value = \"/run_sse\", produces = MediaType.TEXT_EVENT_STREAM_VALUE)\n public SseEmitter agentRunSse(@RequestBody AgentRunRequest request) {\n SseEmitter emitter = new SseEmitter();\n\n if (request.appName == null || request.appName.trim().isEmpty()) {\n log.warn(\n \"appName cannot be null or empty in SseEmitter request for appName: {}, session: {}\",\n request.appName,\n request.sessionId);\n emitter.completeWithError(\n new ResponseStatusException(HttpStatus.BAD_REQUEST, \"appName cannot be null or empty\"));\n return emitter;\n }\n if (request.sessionId == null || request.sessionId.trim().isEmpty()) {\n log.warn(\n \"sessionId cannot be null or empty in SseEmitter request for appName: {}, session: {}\",\n request.appName,\n request.sessionId);\n emitter.completeWithError(\n new ResponseStatusException(\n HttpStatus.BAD_REQUEST, \"sessionId cannot be null or empty\"));\n return emitter;\n }\n\n log.info(\n \"SseEmitter Request received for POST /run_sse_emitter for session: {}\",\n request.sessionId);\n\n final String sessionId = request.sessionId;\n sseExecutor.execute(\n () -> {\n Runner runner;\n try {\n runner = this.runnerService.getRunner(request.appName);\n } catch (ResponseStatusException e) {\n log.warn(\n \"Setup failed for SseEmitter request for session {}: {}\",\n sessionId,\n e.getMessage());\n try {\n emitter.completeWithError(e);\n } catch (Exception ex) {\n log.warn(\n \"Error completing emitter after setup failure for session {}: {}\",\n sessionId,\n ex.getMessage());\n }\n return;\n }\n\n final RunConfig runConfig =\n RunConfig.builder()\n .setStreamingMode(\n request.getStreaming() ? StreamingMode.SSE : StreamingMode.NONE)\n .build();\n\n Flowable eventFlowable =\n runner.runAsync(request.userId, request.sessionId, request.newMessage, runConfig);\n\n Disposable disposable =\n eventFlowable\n .observeOn(Schedulers.io())\n .subscribe(\n event -> {\n try {\n log.debug(\n \"SseEmitter: Sending event {} for session {}\",\n event.id(),\n sessionId);\n emitter.send(SseEmitter.event().data(event.toJson()));\n } catch (IOException e) {\n log.error(\n \"SseEmitter: IOException sending event for session {}: {}\",\n sessionId,\n e.getMessage());\n throw new RuntimeException(\"Failed to send event\", e);\n } catch (Exception e) {\n log.error(\n \"SseEmitter: Unexpected error sending event for session {}: {}\",\n sessionId,\n e.getMessage(),\n e);\n throw new RuntimeException(\"Unexpected error sending event\", e);\n }\n },\n error -> {\n log.error(\n \"SseEmitter: Stream error for session {}: {}\",\n sessionId,\n error.getMessage(),\n error);\n try {\n emitter.completeWithError(error);\n } catch (Exception ex) {\n log.warn(\n \"Error completing emitter after stream error for session {}: {}\",\n sessionId,\n ex.getMessage());\n }\n },\n () -> {\n log.debug(\n \"SseEmitter: Stream completed normally for session: {}\", sessionId);\n try {\n emitter.complete();\n } catch (Exception ex) {\n log.warn(\n \"Error completing emitter after normal completion for session {}:\"\n + \" {}\",\n sessionId,\n ex.getMessage());\n }\n });\n emitter.onCompletion(\n () -> {\n log.debug(\n \"SseEmitter: onCompletion callback for session: {}. Disposing subscription.\",\n sessionId);\n if (!disposable.isDisposed()) {\n disposable.dispose();\n }\n });\n emitter.onTimeout(\n () -> {\n log.debug(\n \"SseEmitter: onTimeout callback for session: {}. Disposing subscription and\"\n + \" completing.\",\n sessionId);\n if (!disposable.isDisposed()) {\n disposable.dispose();\n }\n emitter.complete();\n });\n });\n\n log.debug(\"SseEmitter: Returning emitter for session: {}\", sessionId);\n return emitter;\n }\n\n /**\n * Endpoint to get a graph representation of an event (currently returns a placeholder).\n * Requires Graphviz or similar tooling for full implementation.\n *\n * @param appName Application name.\n * @param userId User ID.\n * @param sessionId Session ID.\n * @param eventId Event ID.\n * @return ResponseEntity containing a GraphResponse with placeholder DOT source.\n * @throws ResponseStatusException if the session or event is not found.\n */\n @GetMapping(\"/apps/{appName}/users/{userId}/sessions/{sessionId}/events/{eventId}/graph\")\n public ResponseEntity getEventGraph(\n @PathVariable String appName,\n @PathVariable String userId,\n @PathVariable String sessionId,\n @PathVariable String eventId) {\n log.info(\n \"Request received for GET /apps/{}/users/{}/sessions/{}/events/{}/graph\",\n appName,\n userId,\n sessionId,\n eventId);\n\n BaseAgent currentAppAgent = agentRegistry.get(appName);\n if (currentAppAgent == null) {\n log.warn(\"Agent app '{}' not found for graph generation.\", appName);\n return ResponseEntity.status(HttpStatus.NOT_FOUND)\n .body(new GraphResponse(\"Agent app not found: \" + appName));\n }\n\n Session session = findSessionOrThrow(appName, userId, sessionId);\n Event event =\n session.events().stream()\n .filter(e -> Objects.equals(e.id(), eventId))\n .findFirst()\n .orElse(null);\n\n if (event == null) {\n log.warn(\"Event {} not found in session {}\", eventId, sessionId);\n return ResponseEntity.ok(new GraphResponse(null));\n }\n\n log.debug(\"Found event {} for graph generation.\", eventId);\n\n List> highlightPairs = new ArrayList<>();\n String eventAuthor = event.author();\n List functionCalls = event.functionCalls();\n List functionResponses = event.functionResponses();\n\n if (!functionCalls.isEmpty()) {\n log.debug(\"Processing {} function calls for highlighting.\", functionCalls.size());\n for (FunctionCall fc : functionCalls) {\n Optional toolName = fc.name();\n if (toolName.isPresent() && !toolName.get().isEmpty()) {\n highlightPairs.add(ImmutableList.of(eventAuthor, toolName.get()));\n log.trace(\"Adding function call highlight: {} -> {}\", eventAuthor, toolName.get());\n }\n }\n } else if (!functionResponses.isEmpty()) {\n log.debug(\"Processing {} function responses for highlighting.\", functionResponses.size());\n for (FunctionResponse fr : functionResponses) {\n Optional toolName = fr.name();\n if (toolName.isPresent() && !toolName.get().isEmpty()) {\n highlightPairs.add(ImmutableList.of(toolName.get(), eventAuthor));\n log.trace(\"Adding function response highlight: {} -> {}\", toolName.get(), eventAuthor);\n }\n }\n } else {\n log.debug(\"Processing simple event, highlighting author: {}\", eventAuthor);\n highlightPairs.add(ImmutableList.of(eventAuthor, eventAuthor));\n }\n\n Optional dotSourceOpt =\n AgentGraphGenerator.getAgentGraphDotSource(currentAppAgent, highlightPairs);\n\n if (dotSourceOpt.isPresent()) {\n log.debug(\"Successfully generated graph DOT source for event {}\", eventId);\n return ResponseEntity.ok(new GraphResponse(dotSourceOpt.get()));\n } else {\n log.warn(\n \"Failed to generate graph DOT source for event {} with agent {}\",\n eventId,\n currentAppAgent.name());\n return ResponseEntity.ok(new GraphResponse(\"Could not generate graph for this event.\"));\n }\n }\n\n /** Placeholder for creating an evaluation set. */\n @PostMapping(\"/apps/{appName}/eval_sets/{evalSetId}\")\n public ResponseEntity createEvalSet(\n @PathVariable String appName, @PathVariable String evalSetId) {\n log.warn(\"Endpoint /apps/{}/eval_sets/{} (POST) is not implemented\", appName, evalSetId);\n return ResponseEntity.status(HttpStatus.NOT_IMPLEMENTED)\n .body(Collections.singletonMap(\"message\", \"Eval set creation not implemented\"));\n }\n\n /** Placeholder for listing evaluation sets. */\n @GetMapping(\"/apps/{appName}/eval_sets\")\n public List listEvalSets(@PathVariable String appName) {\n log.warn(\"Endpoint /apps/{}/eval_sets (GET) is not implemented\", appName);\n return Collections.emptyList();\n }\n\n /** Placeholder for adding a session to an evaluation set. */\n @PostMapping(\"/apps/{appName}/eval_sets/{evalSetId}/add-session\")\n public ResponseEntity addSessionToEvalSet(\n @PathVariable String appName,\n @PathVariable String evalSetId,\n @RequestBody AddSessionToEvalSetRequest req) {\n log.warn(\n \"Endpoint /apps/{}/eval_sets/{}/add-session is not implemented. Request details:\"\n + \" evalId={}, sessionId={}, userId={}\",\n appName,\n evalSetId,\n req.getEvalId(),\n req.getSessionId(),\n req.getUserId());\n return ResponseEntity.status(HttpStatus.NOT_IMPLEMENTED)\n .body(Collections.singletonMap(\"message\", \"Adding session to eval set not implemented\"));\n }\n\n /** Placeholder for listing evaluations within an evaluation set. */\n @GetMapping(\"/apps/{appName}/eval_sets/{evalSetId}/evals\")\n public List listEvalsInEvalSet(\n @PathVariable String appName, @PathVariable String evalSetId) {\n log.warn(\"Endpoint /apps/{}/eval_sets/{}/evals is not implemented\", appName, evalSetId);\n return Collections.emptyList();\n }\n\n /** Placeholder for running evaluations. */\n @PostMapping(\"/apps/{appName}/eval_sets/{evalSetId}/run-eval\")\n public List runEval(\n @PathVariable String appName,\n @PathVariable String evalSetId,\n @RequestBody RunEvalRequest req) {\n log.warn(\n \"Endpoint /apps/{}/eval_sets/{}/run-eval is not implemented. Request details: evalIds={},\"\n + \" evalMetrics={}\",\n appName,\n evalSetId,\n req.getEvalIds(),\n req.getEvalMetrics());\n return Collections.emptyList();\n }\n\n /**\n * Gets a specific evaluation result. (STUB - Not Implemented)\n *\n * @param appName The application name.\n * @param evalResultId The evaluation result ID.\n * @return A ResponseEntity indicating the endpoint is not implemented.\n */\n @GetMapping(\"/apps/{appName}/eval_results/{evalResultId}\")\n public ResponseEntity getEvalResult(\n @PathVariable String appName, @PathVariable String evalResultId) {\n log.warn(\"Endpoint /apps/{}/eval_results/{} (GET) is not implemented\", appName, evalResultId);\n return ResponseEntity.status(HttpStatus.NOT_IMPLEMENTED)\n .body(Collections.singletonMap(\"message\", \"Get evaluation result not implemented\"));\n }\n\n /**\n * Lists all evaluation results for an app. (STUB - Not Implemented)\n *\n * @param appName The application name.\n * @return An empty list, as this endpoint is not implemented.\n */\n @GetMapping(\"/apps/{appName}/eval_results\")\n public List listEvalResults(@PathVariable String appName) {\n log.warn(\"Endpoint /apps/{}/eval_results (GET) is not implemented\", appName);\n return Collections.emptyList();\n }\n }\n\n /** Configuration class for WebSocket handling. */\n @Configuration\n @EnableWebSocket\n public static class WebSocketConfig implements WebSocketConfigurer {\n\n private final LiveWebSocketHandler liveWebSocketHandler;\n\n @Autowired\n public WebSocketConfig(LiveWebSocketHandler liveWebSocketHandler) {\n this.liveWebSocketHandler = liveWebSocketHandler;\n }\n\n @Override\n public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {\n registry.addHandler(liveWebSocketHandler, \"/run_live\").setAllowedOrigins(\"*\");\n }\n }\n\n /**\n * WebSocket Handler for the /run_live endpoint.\n *\n *

Manages bidirectional communication for live agent interactions. Assumes the\n * com.google.adk.runner.Runner class has a method: {@code public Flowable runLive(Session\n * session, Flowable liveRequests, List modalities)}\n */\n @Component\n public static class LiveWebSocketHandler extends TextWebSocketHandler {\n private static final Logger log = LoggerFactory.getLogger(LiveWebSocketHandler.class);\n private static final String LIVE_REQUEST_QUEUE_ATTR = \"liveRequestQueue\";\n private static final String LIVE_SUBSCRIPTION_ATTR = \"liveSubscription\";\n private static final int WEBSOCKET_MAX_BYTES_FOR_REASON = 123;\n\n private final ObjectMapper objectMapper;\n private final BaseSessionService sessionService;\n private final RunnerService runnerService;\n\n @Autowired\n public LiveWebSocketHandler(\n ObjectMapper objectMapper, BaseSessionService sessionService, RunnerService runnerService) {\n this.objectMapper = objectMapper;\n this.sessionService = sessionService;\n this.runnerService = runnerService;\n }\n\n @Override\n public void afterConnectionEstablished(WebSocketSession wsSession) throws Exception {\n URI uri = wsSession.getUri();\n if (uri == null) {\n log.warn(\"WebSocket session URI is null, cannot establish connection.\");\n wsSession.close(CloseStatus.SERVER_ERROR.withReason(\"Invalid URI\"));\n return;\n }\n String path = uri.getPath();\n log.info(\"WebSocket connection established: {} from {}\", wsSession.getId(), uri);\n\n MultiValueMap queryParams =\n UriComponentsBuilder.fromUri(uri).build().getQueryParams();\n String appName = queryParams.getFirst(\"app_name\");\n String userId = queryParams.getFirst(\"user_id\");\n String sessionId = queryParams.getFirst(\"session_id\");\n\n if (appName == null || appName.trim().isEmpty()) {\n log.warn(\n \"WebSocket connection for session {} rejected: app_name query parameter is required and\"\n + \" cannot be empty. URI: {}\",\n wsSession.getId(),\n uri);\n wsSession.close(\n CloseStatus.POLICY_VIOLATION.withReason(\n \"app_name query parameter is required and cannot be empty\"));\n return;\n }\n if (sessionId == null || sessionId.trim().isEmpty()) {\n log.warn(\n \"WebSocket connection for session {} rejected: session_id query parameter is required\"\n + \" and cannot be empty. URI: {}\",\n wsSession.getId(),\n uri);\n wsSession.close(\n CloseStatus.POLICY_VIOLATION.withReason(\n \"session_id query parameter is required and cannot be empty\"));\n return;\n }\n\n log.debug(\n \"Extracted params for WebSocket session {}: appName={}, userId={}, sessionId={},\",\n wsSession.getId(),\n appName,\n userId,\n sessionId);\n\n RunConfig runConfig =\n RunConfig.builder()\n .setResponseModalities(ImmutableList.of(new Modality(Modality.Known.AUDIO)))\n .setStreamingMode(StreamingMode.BIDI)\n .build();\n\n Session session;\n try {\n session =\n sessionService.getSession(appName, userId, sessionId, Optional.empty()).blockingGet();\n if (session == null) {\n log.warn(\n \"Session not found for WebSocket: app={}, user={}, id={}. Closing connection.\",\n appName,\n userId,\n sessionId);\n wsSession.close(new CloseStatus(1002, \"Session not found\")); // 1002: Protocol Error\n return;\n }\n } catch (Exception e) {\n log.error(\n \"Error retrieving session for WebSocket: app={}, user={}, id={}\",\n appName,\n userId,\n sessionId,\n e);\n wsSession.close(CloseStatus.SERVER_ERROR.withReason(\"Failed to retrieve session\"));\n return;\n }\n\n LiveRequestQueue liveRequestQueue = new LiveRequestQueue();\n wsSession.getAttributes().put(LIVE_REQUEST_QUEUE_ATTR, liveRequestQueue);\n\n Runner runner;\n try {\n runner = this.runnerService.getRunner(appName);\n } catch (ResponseStatusException e) {\n log.error(\n \"Failed to get runner for app {} during WebSocket connection: {}\",\n appName,\n e.getMessage());\n wsSession.close(\n CloseStatus.SERVER_ERROR.withReason(\"Runner unavailable: \" + e.getReason()));\n return;\n }\n\n Flowable eventStream = runner.runLive(session, liveRequestQueue, runConfig);\n\n Disposable disposable =\n eventStream\n .subscribeOn(Schedulers.io()) // Offload runner work\n .observeOn(Schedulers.io()) // Send messages on I/O threads\n .subscribe(\n event -> {\n try {\n String jsonEvent = objectMapper.writeValueAsString(event);\n log.debug(\n \"Sending event via WebSocket session {}: {}\",\n wsSession.getId(),\n jsonEvent);\n wsSession.sendMessage(new TextMessage(jsonEvent));\n } catch (JsonProcessingException e) {\n log.error(\n \"Error serializing event to JSON for WebSocket session {}\",\n wsSession.getId(),\n e);\n // Decide if to close session or just log\n } catch (IOException e) {\n log.error(\n \"IOException sending message via WebSocket session {}\",\n wsSession.getId(),\n e);\n // This might mean the session is already closed or problematic\n // Consider closing/disposing here\n try {\n wsSession.close(\n CloseStatus.SERVER_ERROR.withReason(\"Error sending message\"));\n } catch (IOException ignored) {\n }\n }\n },\n error -> {\n log.error(\n \"Error in run_live stream for WebSocket session {}: {}\",\n wsSession.getId(),\n error.getMessage(),\n error);\n String reason =\n error.getMessage() != null ? error.getMessage() : \"Unknown error\";\n try {\n wsSession.close(\n new CloseStatus(\n 1011, // Internal Server Error for WebSocket\n reason.substring(\n 0, Math.min(reason.length(), WEBSOCKET_MAX_BYTES_FOR_REASON))));\n } catch (IOException ignored) {\n }\n },\n () -> {\n log.debug(\n \"run_live stream completed for WebSocket session {}\", wsSession.getId());\n try {\n wsSession.close(CloseStatus.NORMAL);\n } catch (IOException ignored) {\n }\n });\n wsSession.getAttributes().put(LIVE_SUBSCRIPTION_ATTR, disposable);\n log.debug(\"Live run started for WebSocket session {}\", wsSession.getId());\n }\n\n @Override\n protected void handleTextMessage(WebSocketSession wsSession, TextMessage message)\n throws Exception {\n LiveRequestQueue liveRequestQueue =\n (LiveRequestQueue) wsSession.getAttributes().get(LIVE_REQUEST_QUEUE_ATTR);\n\n if (liveRequestQueue == null) {\n log.warn(\n \"Received message on WebSocket session {} but LiveRequestQueue is not available (null).\"\n + \" Message: {}\",\n wsSession.getId(),\n message.getPayload());\n return;\n }\n\n try {\n String payload = message.getPayload();\n log.debug(\"Received text message on WebSocket session {}: {}\", wsSession.getId(), payload);\n\n JsonNode rootNode = objectMapper.readTree(payload);\n LiveRequest.Builder liveRequestBuilder = LiveRequest.builder();\n\n if (rootNode.has(\"content\")) {\n Content content = objectMapper.treeToValue(rootNode.get(\"content\"), Content.class);\n liveRequestBuilder.content(content);\n }\n\n if (rootNode.has(\"blob\")) {\n JsonNode blobNode = rootNode.get(\"blob\");\n Blob.Builder blobBuilder = Blob.builder();\n if (blobNode.has(\"displayName\")) {\n blobBuilder.displayName(blobNode.get(\"displayName\").asText());\n }\n if (blobNode.has(\"data\")) {\n blobBuilder.data(blobNode.get(\"data\").binaryValue());\n }\n // Handle both mime_type and mimeType. Blob states mimeType but we get mime_type from the\n // frontend.\n String mimeType =\n blobNode.has(\"mimeType\")\n ? blobNode.get(\"mimeType\").asText()\n : (blobNode.has(\"mime_type\") ? blobNode.get(\"mime_type\").asText() : null);\n if (mimeType != null) {\n blobBuilder.mimeType(mimeType);\n }\n liveRequestBuilder.blob(blobBuilder.build());\n }\n LiveRequest liveRequest = liveRequestBuilder.build();\n liveRequestQueue.send(liveRequest);\n } catch (JsonProcessingException e) {\n log.error(\n \"Error deserializing LiveRequest from WebSocket message for session {}: {}\",\n wsSession.getId(),\n message.getPayload(),\n e);\n wsSession.sendMessage(\n new TextMessage(\n \"{\\\"error\\\":\\\"Invalid JSON format for LiveRequest\\\", \\\"details\\\":\\\"\"\n + e.getMessage()\n + \"\\\"}\"));\n } catch (Exception e) {\n log.error(\n \"Unexpected error processing text message for WebSocket session {}: {}\",\n wsSession.getId(),\n message.getPayload(),\n e);\n String reason = e.getMessage() != null ? e.getMessage() : \"Error processing message\";\n wsSession.close(\n new CloseStatus(\n 1011,\n reason.substring(0, Math.min(reason.length(), WEBSOCKET_MAX_BYTES_FOR_REASON))));\n }\n }\n\n @Override\n public void handleTransportError(WebSocketSession wsSession, Throwable exception)\n throws Exception {\n log.error(\n \"WebSocket transport error for session {}: {}\",\n wsSession.getId(),\n exception.getMessage(),\n exception);\n // Cleanup resources similar to afterConnectionClosed\n cleanupSession(wsSession);\n if (wsSession.isOpen()) {\n String reason = exception.getMessage() != null ? exception.getMessage() : \"Transport error\";\n wsSession.close(\n CloseStatus.PROTOCOL_ERROR.withReason(\n reason.substring(0, Math.min(reason.length(), WEBSOCKET_MAX_BYTES_FOR_REASON))));\n }\n }\n\n @Override\n public void afterConnectionClosed(WebSocketSession wsSession, CloseStatus status)\n throws Exception {\n log.info(\n \"WebSocket connection closed: {} with status {}\", wsSession.getId(), status.toString());\n cleanupSession(wsSession);\n }\n\n private void cleanupSession(WebSocketSession wsSession) {\n LiveRequestQueue liveRequestQueue =\n (LiveRequestQueue) wsSession.getAttributes().remove(LIVE_REQUEST_QUEUE_ATTR);\n if (liveRequestQueue != null) {\n liveRequestQueue.close(); // Signal end of input to the runner\n log.debug(\"Called close() on LiveRequestQueue for session {}\", wsSession.getId());\n }\n\n Disposable disposable = (Disposable) wsSession.getAttributes().remove(LIVE_SUBSCRIPTION_ATTR);\n if (disposable != null && !disposable.isDisposed()) {\n disposable.dispose();\n }\n log.debug(\"Cleaned up resources for WebSocket session {}\", wsSession.getId());\n }\n }\n\n /**\n * Main entry point for the Spring Boot application.\n *\n * @param args Command line arguments.\n */\n public static void main(String[] args) {\n System.setProperty(\n \"org.apache.tomcat.websocket.DEFAULT_BUFFER_SIZE\", String.valueOf(10 * 1024 * 1024));\n SpringApplication.run(AdkWebServer.class, args);\n log.info(\"AdkWebServer application started successfully.\");\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/memory/InMemoryMemoryService.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.memory;\n\nimport static com.google.common.collect.ImmutableList.toImmutableList;\n\nimport com.google.adk.events.Event;\nimport com.google.adk.sessions.Session;\nimport com.google.common.base.Strings;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.genai.types.Part;\nimport io.reactivex.rxjava3.core.Completable;\nimport io.reactivex.rxjava3.core.Single;\nimport java.time.Instant;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\n/**\n * An in-memory memory service for prototyping purposes only.\n *\n *

Uses keyword matching instead of semantic search.\n */\npublic final class InMemoryMemoryService implements BaseMemoryService {\n\n // Pattern to extract words, matching the Python version.\n private static final Pattern WORD_PATTERN = Pattern.compile(\"[A-Za-z]+\");\n\n /** Keys are \"app_name/user_id\", values are maps of \"session_id\" to a list of events. */\n private final Map>> sessionEvents;\n\n public InMemoryMemoryService() {\n this.sessionEvents = new ConcurrentHashMap<>();\n }\n\n private static String userKey(String appName, String userId) {\n return appName + \"/\" + userId;\n }\n\n @Override\n public Completable addSessionToMemory(Session session) {\n return Completable.fromAction(\n () -> {\n String key = userKey(session.appName(), session.userId());\n Map> userSessions =\n sessionEvents.computeIfAbsent(key, k -> new ConcurrentHashMap<>());\n ImmutableList nonEmptyEvents =\n session.events().stream()\n .filter(\n event ->\n event.content().isPresent()\n && event.content().get().parts().isPresent()\n && !event.content().get().parts().get().isEmpty())\n .collect(toImmutableList());\n userSessions.put(session.id(), nonEmptyEvents);\n });\n }\n\n @Override\n public Single searchMemory(String appName, String userId, String query) {\n return Single.fromCallable(\n () -> {\n String key = userKey(appName, userId);\n\n if (!sessionEvents.containsKey(key)) {\n return SearchMemoryResponse.builder().build();\n }\n\n Map> userSessions = sessionEvents.get(key);\n\n ImmutableSet wordsInQuery =\n ImmutableSet.copyOf(query.toLowerCase(Locale.ROOT).split(\"\\\\s+\"));\n\n List matchingMemories = new ArrayList<>();\n\n for (List eventsInSession : userSessions.values()) {\n for (Event event : eventsInSession) {\n if (event.content().isEmpty() || event.content().get().parts().isEmpty()) {\n continue;\n }\n\n Set wordsInEvent = new HashSet<>();\n for (Part part : event.content().get().parts().get()) {\n if (!Strings.isNullOrEmpty(part.text().get())) {\n Matcher matcher = WORD_PATTERN.matcher(part.text().get());\n while (matcher.find()) {\n wordsInEvent.add(matcher.group().toLowerCase(Locale.ROOT));\n }\n }\n }\n\n if (wordsInEvent.isEmpty()) {\n continue;\n }\n\n if (!Collections.disjoint(wordsInQuery, wordsInEvent)) {\n MemoryEntry memory =\n MemoryEntry.builder()\n .setContent(event.content().get())\n .setAuthor(event.author())\n .setTimestamp(formatTimestamp(event.timestamp()))\n .build();\n matchingMemories.add(memory);\n }\n }\n }\n\n return SearchMemoryResponse.builder()\n .setMemories(ImmutableList.copyOf(matchingMemories))\n .build();\n });\n }\n\n private String formatTimestamp(long timestamp) {\n return Instant.ofEpochSecond(timestamp).toString();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/runner/Runner.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.runner;\n\nimport com.google.adk.Telemetry;\nimport com.google.adk.agents.BaseAgent;\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.agents.LiveRequestQueue;\nimport com.google.adk.agents.LlmAgent;\nimport com.google.adk.agents.RunConfig;\nimport com.google.adk.artifacts.BaseArtifactService;\nimport com.google.adk.events.Event;\nimport com.google.adk.sessions.BaseSessionService;\nimport com.google.adk.sessions.Session;\nimport com.google.adk.utils.CollectionUtils;\nimport com.google.common.collect.ImmutableList;\nimport com.google.genai.types.AudioTranscriptionConfig;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.Modality;\nimport com.google.genai.types.Part;\nimport io.opentelemetry.api.trace.Span;\nimport io.opentelemetry.api.trace.StatusCode;\nimport io.opentelemetry.context.Scope;\nimport io.reactivex.rxjava3.core.Flowable;\nimport io.reactivex.rxjava3.core.Maybe;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Optional;\n\n/** The main class for the GenAI Agents runner. */\npublic class Runner {\n private final BaseAgent agent;\n private final String appName;\n private final BaseArtifactService artifactService;\n private final BaseSessionService sessionService;\n\n /** Creates a new {@code Runner}. */\n public Runner(\n BaseAgent agent,\n String appName,\n BaseArtifactService artifactService,\n BaseSessionService sessionService) {\n this.agent = agent;\n this.appName = appName;\n this.artifactService = artifactService;\n this.sessionService = sessionService;\n }\n\n public BaseAgent agent() {\n return this.agent;\n }\n\n public String appName() {\n return this.appName;\n }\n\n public BaseArtifactService artifactService() {\n return this.artifactService;\n }\n\n public BaseSessionService sessionService() {\n return this.sessionService;\n }\n\n /**\n * Appends a new user message to the session history.\n *\n * @throws IllegalArgumentException if message has no parts.\n */\n private void appendNewMessageToSession(\n Session session,\n Content newMessage,\n InvocationContext invocationContext,\n boolean saveInputBlobsAsArtifacts) {\n if (newMessage.parts().isEmpty()) {\n throw new IllegalArgumentException(\"No parts in the new_message.\");\n }\n\n if (this.artifactService != null && saveInputBlobsAsArtifacts) {\n // The runner directly saves the artifacts (if applicable) in the\n // user message and replaces the artifact data with a file name\n // placeholder.\n for (int i = 0; i < newMessage.parts().get().size(); i++) {\n Part part = newMessage.parts().get().get(i);\n if (part.inlineData().isEmpty()) {\n continue;\n }\n String fileName = \"artifact_\" + invocationContext.invocationId() + \"_\" + i;\n var unused =\n this.artifactService.saveArtifact(\n this.appName, session.userId(), session.id(), fileName, part);\n\n newMessage\n .parts()\n .get()\n .set(\n i,\n Part.fromText(\n \"Uploaded file: \" + fileName + \". It has been saved to the artifacts\"));\n }\n }\n // Appends only. We do not yield the event because it's not from the model.\n Event event =\n Event.builder()\n .id(Event.generateEventId())\n .invocationId(invocationContext.invocationId())\n .author(\"user\")\n .content(Optional.of(newMessage))\n .build();\n this.sessionService.appendEvent(session, event);\n }\n\n /**\n * Runs the agent in the standard mode.\n *\n * @param userId The ID of the user for the session.\n * @param sessionId The ID of the session to run the agent in.\n * @param newMessage The new message from the user to process.\n * @param runConfig Configuration for the agent run.\n * @return A Flowable stream of {@link Event} objects generated by the agent during execution.\n */\n public Flowable runAsync(\n String userId, String sessionId, Content newMessage, RunConfig runConfig) {\n Maybe maybeSession =\n this.sessionService.getSession(appName, userId, sessionId, Optional.empty());\n return maybeSession\n .switchIfEmpty(\n Single.error(\n new IllegalArgumentException(\n String.format(\"Session not found: %s for user %s\", sessionId, userId))))\n .flatMapPublisher(session -> this.runAsync(session, newMessage, runConfig));\n }\n\n /**\n * Asynchronously runs the agent for a given user and session, processing a new message and using\n * a default {@link RunConfig}.\n *\n *

This method initiates an agent execution within the specified session, appending the\n * provided new message to the session's history. It utilizes a default {@code RunConfig} to\n * control execution parameters. The method returns a stream of {@link Event} objects representing\n * the agent's activity during the run.\n *\n * @param userId The ID of the user initiating the session.\n * @param sessionId The ID of the session in which the agent will run.\n * @param newMessage The new {@link Content} message to be processed by the agent.\n * @return A {@link Flowable} emitting {@link Event} objects generated by the agent.\n */\n public Flowable runAsync(String userId, String sessionId, Content newMessage) {\n return runAsync(userId, sessionId, newMessage, RunConfig.builder().build());\n }\n\n /**\n * Runs the agent in the standard mode using a provided Session object.\n *\n * @param session The session to run the agent in.\n * @param newMessage The new message from the user to process.\n * @param runConfig Configuration for the agent run.\n * @return A Flowable stream of {@link Event} objects generated by the agent during execution.\n */\n public Flowable runAsync(Session session, Content newMessage, RunConfig runConfig) {\n Span span = Telemetry.getTracer().spanBuilder(\"invocation\").startSpan();\n try (Scope scope = span.makeCurrent()) {\n return Flowable.just(session)\n .flatMap(\n sess -> {\n BaseAgent rootAgent = this.agent;\n InvocationContext invocationContext =\n InvocationContext.create(\n this.sessionService,\n this.artifactService,\n InvocationContext.newInvocationContextId(),\n rootAgent,\n sess,\n newMessage,\n runConfig);\n\n if (newMessage != null) {\n appendNewMessageToSession(\n sess, newMessage, invocationContext, runConfig.saveInputBlobsAsArtifacts());\n }\n\n invocationContext.agent(this.findAgentToRun(sess, rootAgent));\n Flowable events = invocationContext.agent().runAsync(invocationContext);\n return events.doOnNext(event -> this.sessionService.appendEvent(sess, event));\n })\n .doOnError(\n throwable -> {\n span.setStatus(StatusCode.ERROR, \"Error in runAsync Flowable execution\");\n span.recordException(throwable);\n })\n .doFinally(span::end);\n } catch (Throwable t) {\n span.setStatus(StatusCode.ERROR, \"Error during runAsync synchronous setup\");\n span.recordException(t);\n span.end();\n return Flowable.error(t);\n }\n }\n\n /**\n * Creates an {@link InvocationContext} for a live (streaming) run.\n *\n * @return invocation context configured for a live run.\n */\n private InvocationContext newInvocationContextForLive(\n Session session, Optional liveRequestQueue, RunConfig runConfig) {\n RunConfig.Builder runConfigBuilder = RunConfig.builder(runConfig);\n if (!CollectionUtils.isNullOrEmpty(runConfig.responseModalities())\n && liveRequestQueue.isPresent()) {\n // Default to AUDIO modality if not specified.\n if (CollectionUtils.isNullOrEmpty(runConfig.responseModalities())) {\n runConfigBuilder.setResponseModalities(\n ImmutableList.of(new Modality(Modality.Known.AUDIO)));\n if (runConfig.outputAudioTranscription() == null) {\n runConfigBuilder.setOutputAudioTranscription(AudioTranscriptionConfig.builder().build());\n }\n } else if (!runConfig.responseModalities().contains(new Modality(Modality.Known.TEXT))) {\n if (runConfig.outputAudioTranscription() == null) {\n runConfigBuilder.setOutputAudioTranscription(AudioTranscriptionConfig.builder().build());\n }\n }\n }\n return newInvocationContext(session, liveRequestQueue, runConfigBuilder.build());\n }\n\n /**\n * Creates an {@link InvocationContext} for the given session, request queue, and config.\n *\n * @return a new {@link InvocationContext}.\n */\n private InvocationContext newInvocationContext(\n Session session, Optional liveRequestQueue, RunConfig runConfig) {\n BaseAgent rootAgent = this.agent;\n InvocationContext invocationContext =\n InvocationContext.create(\n this.sessionService,\n this.artifactService,\n rootAgent,\n session,\n liveRequestQueue.orElse(null),\n runConfig);\n invocationContext.agent(this.findAgentToRun(session, rootAgent));\n return invocationContext;\n }\n\n /**\n * Runs the agent in live mode, appending generated events to the session.\n *\n * @return stream of events from the agent.\n */\n public Flowable runLive(\n Session session, LiveRequestQueue liveRequestQueue, RunConfig runConfig) {\n Span span = Telemetry.getTracer().spanBuilder(\"invocation\").startSpan();\n try (Scope scope = span.makeCurrent()) {\n InvocationContext invocationContext =\n newInvocationContextForLive(session, Optional.of(liveRequestQueue), runConfig);\n return invocationContext\n .agent()\n .runLive(invocationContext)\n .doOnNext(event -> this.sessionService.appendEvent(session, event))\n .doOnError(\n throwable -> {\n span.setStatus(StatusCode.ERROR, \"Error in runLive Flowable execution\");\n span.recordException(throwable);\n })\n .doFinally(span::end);\n } catch (Throwable t) {\n span.setStatus(StatusCode.ERROR, \"Error during runLive synchronous setup\");\n span.recordException(t);\n span.end();\n return Flowable.error(t);\n }\n }\n\n /**\n * Retrieves the session and runs the agent in live mode.\n *\n * @return stream of events from the agent.\n * @throws IllegalArgumentException if the session is not found.\n */\n public Flowable runLive(\n String userId, String sessionId, LiveRequestQueue liveRequestQueue, RunConfig runConfig) {\n return this.sessionService\n .getSession(appName, userId, sessionId, Optional.empty())\n .flatMapPublisher(\n session -> {\n if (session == null) {\n return Flowable.error(\n new IllegalArgumentException(\n String.format(\"Session not found: %s for user %s\", sessionId, userId)));\n }\n return this.runLive(session, liveRequestQueue, runConfig);\n });\n }\n\n /**\n * Runs the agent asynchronously with a default user ID.\n *\n * @return stream of generated events.\n */\n public Flowable runWithSessionId(\n String sessionId, Content newMessage, RunConfig runConfig) {\n // TODO(b/410859954): Add user_id to getter or method signature. Assuming \"tmp-user\" for now.\n return this.runAsync(\"tmp-user\", sessionId, newMessage, runConfig);\n }\n\n /**\n * Checks if the agent and its parent chain allow transfer up the tree.\n *\n * @return true if transferable, false otherwise.\n */\n private boolean isTransferableAcrossAgentTree(BaseAgent agentToRun) {\n BaseAgent current = agentToRun;\n while (current != null) {\n // Agents eligible to transfer must have an LLM-based agent parent.\n if (!(current instanceof LlmAgent)) {\n return false;\n }\n // If any agent can't transfer to its parent, the chain is broken.\n LlmAgent agent = (LlmAgent) current;\n if (agent.disallowTransferToParent()) {\n return false;\n }\n current = current.parentAgent();\n }\n return true;\n }\n\n /**\n * Returns the agent that should handle the next request based on session history.\n *\n * @return agent to run.\n */\n private BaseAgent findAgentToRun(Session session, BaseAgent rootAgent) {\n List events = new ArrayList<>(session.events());\n Collections.reverse(events);\n\n for (Event event : events) {\n String author = event.author();\n if (author.equals(\"user\")) {\n continue;\n }\n\n if (author.equals(rootAgent.name())) {\n return rootAgent;\n }\n\n BaseAgent agent = rootAgent.findSubAgent(author);\n\n if (agent == null) {\n continue;\n }\n\n if (this.isTransferableAcrossAgentTree(agent)) {\n return agent;\n }\n }\n\n return rootAgent;\n }\n\n // TODO: run statelessly\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/artifacts/InMemoryArtifactService.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.artifacts;\n\nimport static com.google.common.collect.ImmutableList.toImmutableList;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Streams;\nimport com.google.genai.types.Part;\nimport io.reactivex.rxjava3.core.Completable;\nimport io.reactivex.rxjava3.core.Maybe;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.stream.IntStream;\n\n/** An in-memory implementation of the {@link BaseArtifactService}. */\npublic final class InMemoryArtifactService implements BaseArtifactService {\n private final Map>>>> artifacts;\n\n public InMemoryArtifactService() {\n this.artifacts = new HashMap<>();\n }\n\n /**\n * Saves an artifact in memory and assigns a new version.\n *\n * @return Single with assigned version number.\n */\n @Override\n public Single saveArtifact(\n String appName, String userId, String sessionId, String filename, Part artifact) {\n List versions =\n artifacts\n .computeIfAbsent(appName, k -> new HashMap<>())\n .computeIfAbsent(userId, k -> new HashMap<>())\n .computeIfAbsent(sessionId, k -> new HashMap<>())\n .computeIfAbsent(filename, k -> new ArrayList<>());\n versions.add(artifact);\n return Single.just(versions.size() - 1);\n }\n\n /**\n * Loads an artifact by version or latest.\n *\n * @return Maybe with the artifact, or empty if not found.\n */\n @Override\n public Maybe loadArtifact(\n String appName, String userId, String sessionId, String filename, Optional version) {\n List versions =\n artifacts\n .getOrDefault(appName, new HashMap<>())\n .getOrDefault(userId, new HashMap<>())\n .getOrDefault(sessionId, new HashMap<>())\n .getOrDefault(filename, new ArrayList<>());\n\n if (versions.isEmpty()) {\n return Maybe.empty();\n }\n if (version.isPresent()) {\n int v = version.get();\n if (v >= 0 && v < versions.size()) {\n return Maybe.just(versions.get(v));\n } else {\n return Maybe.empty();\n }\n } else {\n return Maybe.fromOptional(Streams.findLast(versions.stream()));\n }\n }\n\n /**\n * Lists filenames of stored artifacts for the session.\n *\n * @return Single with list of artifact filenames.\n */\n @Override\n public Single listArtifactKeys(\n String appName, String userId, String sessionId) {\n return Single.just(\n ListArtifactsResponse.builder()\n .filenames(\n ImmutableList.copyOf(\n artifacts\n .getOrDefault(appName, new HashMap<>())\n .getOrDefault(userId, new HashMap<>())\n .getOrDefault(sessionId, new HashMap<>())\n .keySet()))\n .build());\n }\n\n /**\n * Deletes all versions of the given artifact.\n *\n * @return Completable indicating completion.\n */\n @Override\n public Completable deleteArtifact(\n String appName, String userId, String sessionId, String filename) {\n artifacts\n .getOrDefault(appName, new HashMap<>())\n .getOrDefault(userId, new HashMap<>())\n .getOrDefault(sessionId, new HashMap<>())\n .remove(filename);\n return Completable.complete();\n }\n\n /**\n * Lists all versions of the specified artifact.\n *\n * @return Single with list of version numbers.\n */\n @Override\n public Single> listVersions(\n String appName, String userId, String sessionId, String filename) {\n int size =\n artifacts\n .getOrDefault(appName, new HashMap<>())\n .getOrDefault(userId, new HashMap<>())\n .getOrDefault(sessionId, new HashMap<>())\n .getOrDefault(filename, new ArrayList<>())\n .size();\n if (size == 0) {\n return Single.just(ImmutableList.of());\n }\n return Single.just(IntStream.range(0, size).boxed().collect(toImmutableList()));\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/sessions/Session.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.databind.annotation.JsonDeserialize;\nimport com.google.adk.JsonBaseModel;\nimport com.google.adk.events.Event;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport java.time.Duration;\nimport java.time.Instant;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentMap;\n\n/** A {@link Session} object that encapsulates the {@link State} and {@link Event}s of a session. */\n@JsonDeserialize(builder = Session.Builder.class)\npublic final class Session extends JsonBaseModel {\n private final String id;\n\n private final String appName;\n\n private final String userId;\n\n private final State state;\n\n private final List events;\n\n private Instant lastUpdateTime;\n\n public static Builder builder(String id) {\n return new Builder(id);\n }\n\n /** Builder for {@link Session}. */\n public static final class Builder {\n private String id;\n private String appName;\n private String userId;\n private State state = new State(new ConcurrentHashMap<>());\n private List events = new ArrayList<>();\n private Instant lastUpdateTime = Instant.EPOCH;\n\n public Builder(String id) {\n this.id = id;\n }\n\n @JsonCreator\n private Builder() {}\n\n @CanIgnoreReturnValue\n @JsonProperty(\"id\")\n public Builder id(String id) {\n this.id = id;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder state(State state) {\n this.state = state;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"state\")\n public Builder state(ConcurrentMap state) {\n this.state = new State(state);\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"appName\")\n public Builder appName(String appName) {\n this.appName = appName;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"userId\")\n public Builder userId(String userId) {\n this.userId = userId;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"events\")\n public Builder events(List events) {\n this.events = events;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder lastUpdateTime(Instant lastUpdateTime) {\n this.lastUpdateTime = lastUpdateTime;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"lastUpdateTime\")\n public Builder lastUpdateTimeSeconds(double seconds) {\n long secs = (long) seconds;\n // Convert fractional part to nanoseconds\n long nanos = (long) ((seconds - secs) * Duration.ofSeconds(1).toNanos());\n this.lastUpdateTime = Instant.ofEpochSecond(secs, nanos);\n return this;\n }\n\n public Session build() {\n if (id == null) {\n throw new IllegalStateException(\"Session id is null\");\n }\n return new Session(appName, userId, id, state, events, lastUpdateTime);\n }\n }\n\n @JsonProperty(\"id\")\n public String id() {\n return id;\n }\n\n @JsonProperty(\"state\")\n public ConcurrentMap state() {\n return state;\n }\n\n @JsonProperty(\"events\")\n public List events() {\n return events;\n }\n\n @JsonProperty(\"appName\")\n public String appName() {\n return appName;\n }\n\n @JsonProperty(\"userId\")\n public String userId() {\n return userId;\n }\n\n public void lastUpdateTime(Instant lastUpdateTime) {\n this.lastUpdateTime = lastUpdateTime;\n }\n\n public Instant lastUpdateTime() {\n return lastUpdateTime;\n }\n\n @JsonProperty(\"lastUpdateTime\")\n public double getLastUpdateTimeAsDouble() {\n if (lastUpdateTime == null) {\n return 0.0;\n }\n long seconds = lastUpdateTime.getEpochSecond();\n int nanos = lastUpdateTime.getNano();\n return seconds + nanos / (double) Duration.ofSeconds(1).toNanos();\n }\n\n @Override\n public String toString() {\n return toJson();\n }\n\n public static Session fromJson(String json) {\n return fromJsonString(json, Session.class);\n }\n\n private Session(\n String appName,\n String userId,\n String id,\n State state,\n List events,\n Instant lastUpdateTime) {\n this.id = id;\n this.appName = appName;\n this.userId = userId;\n this.state = state;\n this.events = events;\n this.lastUpdateTime = lastUpdateTime;\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/utils/InstructionUtils.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.utils;\n\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.sessions.Session;\nimport com.google.adk.sessions.State;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.genai.types.Part;\nimport io.reactivex.rxjava3.core.Maybe;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.regex.MatchResult;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\n/** Utility methods for handling instruction templates. */\npublic final class InstructionUtils {\n\n private static final Pattern INSTRUCTION_PLACEHOLDER_PATTERN =\n Pattern.compile(\"\\\\{+[^\\\\{\\\\}]*\\\\}+\");\n\n private InstructionUtils() {}\n\n /**\n * Populates placeholders in an instruction template string with values from the session state or\n * loaded artifacts.\n *\n *

Placeholder Syntax:\n *\n *

Placeholders are enclosed by one or more curly braces at the start and end, e.g., {@code\n * {key}} or {@code {{key}}}. The core {@code key} is extracted from whatever is between the\n * innermost pair of braces after trimming whitespace and possibly removing the {@code ?} which\n * denotes optionality (e.g. {@code {key?}}). The {@code key} itself must not contain curly\n * braces. For typical usage, a single pair of braces like {@code {my_variable}} is standard.\n *\n *

The extracted {@code key} determines the source and name of the value:\n *\n *

    \n *
  • Session State Variables: The {@code key} (e.g., {@code \"variable_name\"} or {@code\n * \"prefix:variable_name\"}) refers to a variable in session state.\n *
      \n *
    • Simple name: {@code {variable_name}}. The {@code variable_name} part must be a\n * valid identifier as per {@link #isValidStateName(String)}. Invalid names will\n * result in the placeholder being returned as is.\n *
    • Prefixed name: {@code {prefix:variable_name}}. Valid prefixes are: {@value\n * com.google.adk.sessions.State#APP_PREFIX}, {@value\n * com.google.adk.sessions.State#USER_PREFIX}, and {@value\n * com.google.adk.sessions.State#TEMP_PREFIX} The part of the name following the\n * prefix must also be a valid identifier. Invalid prefixes will result in the\n * placeholder being returned as is.\n *
    \n *
  • Artifacts: The {@code key} starts with \"{@code artifact.}\" (e.g., {@code\n * \"artifact.file_name\"}).\n *
  • Optional Placeholders: A {@code key} can be marked as optional by appending a\n * question mark {@code ?} at its very end, inside the braces.\n *
      \n *
    • Example: {@code {optional_variable?}}, {@code {{artifact.optional_file.txt?}}}\n *
    • If an optional placeholder cannot be resolved (e.g., variable not found, artifact\n * not found), it is replaced with an empty string.\n *
    \n *
\n *\n * Example Usage:\n *\n *
{@code\n   * InvocationContext context = ...; // Assume this is initialized with session and artifact service\n   * Session session = context.session();\n   *\n   * session.state().put(\"user:name\", \"Alice\");\n   *\n   * context.artifactService().saveArtifact(\n   *     session.appName(), session.userId(), session.id(), \"knowledge.txt\", Part.fromText(\"Origins of the universe: At first, there was-\"));\n   *\n   * String template = \"You are {user:name}'s assistant. Answer questions based on your knowledge. Your knowledge: {artifact.knowledge.txt}.\" +\n   *                   \" Your extra knowledge: {artifact.missing_artifact.txt?}\";\n   *\n   * Single populatedStringSingle = InstructionUtils.injectSessionState(context, template);\n   * populatedStringSingle.subscribe(\n   *     result -> System.out.println(result),\n   *     // Expected: \"You are Alice's assistant. Answer questions based on your knowledge. Your knowledge: Origins of the universe: At first, there was-. Your extra knowledge: \"\n   *     error -> System.err.println(\"Error populating template: \" + error.getMessage())\n   * );\n   * }
\n *\n * @param context The invocation context providing access to session state and artifact services.\n * @param template The instruction template string containing placeholders to be populated.\n * @return A {@link Single} that will emit the populated instruction string upon successful\n * resolution of all non-optional placeholders. Emits the original template if it is empty or\n * contains no placeholders that are processed.\n * @throws NullPointerException if the template or context is null.\n * @throws IllegalArgumentException if a non-optional variable or artifact is not found.\n */\n public static Single injectSessionState(InvocationContext context, String template) {\n if (template == null) {\n return Single.error(new NullPointerException(\"template cannot be null\"));\n }\n if (context == null) {\n return Single.error(new NullPointerException(\"context cannot be null\"));\n }\n Matcher matcher = INSTRUCTION_PLACEHOLDER_PATTERN.matcher(template);\n List> parts = new ArrayList<>();\n int lastEnd = 0;\n\n while (matcher.find()) {\n if (matcher.start() > lastEnd) {\n parts.add(Single.just(template.substring(lastEnd, matcher.start())));\n }\n MatchResult matchResult = matcher.toMatchResult();\n parts.add(resolveMatchAsync(context, matchResult));\n lastEnd = matcher.end();\n }\n if (lastEnd < template.length()) {\n parts.add(Single.just(template.substring(lastEnd)));\n }\n\n if (parts.isEmpty()) {\n return Single.just(template);\n }\n\n return Single.zip(\n parts,\n objects -> {\n StringBuilder sb = new StringBuilder();\n for (Object obj : objects) {\n sb.append(obj);\n }\n return sb.toString();\n });\n }\n\n private static Single resolveMatchAsync(InvocationContext context, MatchResult match) {\n String placeholder = match.group();\n String varNameFromPlaceholder =\n placeholder.replaceAll(\"^\\\\{+\", \"\").replaceAll(\"\\\\}+$\", \"\").trim();\n\n final boolean optional;\n final String cleanVarName;\n if (varNameFromPlaceholder.endsWith(\"?\")) {\n optional = true;\n cleanVarName = varNameFromPlaceholder.substring(0, varNameFromPlaceholder.length() - 1);\n } else {\n optional = false;\n cleanVarName = varNameFromPlaceholder;\n }\n\n if (cleanVarName.startsWith(\"artifact.\")) {\n final String artifactName = cleanVarName.substring(\"artifact.\".length());\n Session session = context.session();\n\n Maybe artifactMaybe =\n context\n .artifactService()\n .loadArtifact(\n session.appName(),\n session.userId(),\n session.id(),\n artifactName,\n Optional.empty());\n\n return artifactMaybe\n .map(Part::toJson)\n .switchIfEmpty(\n Single.defer(\n () -> {\n if (optional) {\n return Single.just(\"\");\n } else {\n return Single.error(\n new IllegalArgumentException(\n String.format(\"Artifact %s not found.\", artifactName)));\n }\n }));\n\n } else if (!isValidStateName(cleanVarName)) {\n return Single.just(placeholder);\n } else if (context.session().state().containsKey(cleanVarName)) {\n Object value = context.session().state().get(cleanVarName);\n return Single.just(String.valueOf(value));\n } else if (optional) {\n return Single.just(\"\");\n } else {\n return Single.error(\n new IllegalArgumentException(\n String.format(\"Context variable not found: `%s`.\", cleanVarName)));\n }\n }\n\n /**\n * Checks if a given string is a valid state variable name.\n *\n *

A valid state variable name must either:\n *\n *

    \n *
  • Be a valid identifier (as defined by {@link Character#isJavaIdentifierStart(int)} and\n * {@link Character#isJavaIdentifierPart(int)}).\n *
  • Start with a valid prefix ({@value com.google.adk.sessions.State#APP_PREFIX}, {@value\n * com.google.adk.sessions.State#USER_PREFIX}, or {@value\n * com.google.adk.sessions.State#TEMP_PREFIX}) followed by a valid identifier.\n *
\n *\n * @param varName The string to check.\n * @return True if the string is a valid state variable name, false otherwise.\n */\n private static boolean isValidStateName(String varName) {\n if (varName.isEmpty()) {\n return false;\n }\n String[] parts = varName.split(\":\", 2);\n if (parts.length == 1) {\n return isValidIdentifier(parts[0]);\n }\n\n if (parts.length == 2) {\n String prefixPart = parts[0] + \":\";\n ImmutableSet validPrefixes =\n ImmutableSet.of(State.APP_PREFIX, State.USER_PREFIX, State.TEMP_PREFIX);\n if (validPrefixes.contains(prefixPart)) {\n return isValidIdentifier(parts[1]);\n }\n }\n return false;\n }\n\n private static boolean isValidIdentifier(String s) {\n if (s.isEmpty()) {\n return false;\n }\n if (!Character.isJavaIdentifierStart(s.charAt(0))) {\n return false;\n }\n for (int i = 1; i < s.length(); i++) {\n if (!Character.isJavaIdentifierPart(s.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/artifacts/GcsArtifactService.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.artifacts;\n\nimport static java.util.Collections.max;\n\nimport com.google.cloud.storage.Blob;\nimport com.google.cloud.storage.BlobId;\nimport com.google.cloud.storage.BlobInfo;\nimport com.google.cloud.storage.Storage;\nimport com.google.cloud.storage.Storage.BlobListOption;\nimport com.google.cloud.storage.StorageException;\nimport com.google.common.base.Splitter;\nimport com.google.common.base.VerifyException;\nimport com.google.common.collect.ImmutableList;\nimport com.google.genai.types.Part;\nimport io.reactivex.rxjava3.core.Completable;\nimport io.reactivex.rxjava3.core.Maybe;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.Set;\n\n/** An artifact service implementation using Google Cloud Storage (GCS). */\npublic final class GcsArtifactService implements BaseArtifactService {\n private final String bucketName;\n private final Storage storageClient;\n\n /**\n * Initializes the GcsArtifactService.\n *\n * @param bucketName The name of the GCS bucket to use.\n * @param storageClient The GCS storage client instance.\n */\n public GcsArtifactService(String bucketName, Storage storageClient) {\n this.bucketName = bucketName;\n this.storageClient = storageClient;\n }\n\n /**\n * Checks if a filename uses the user namespace.\n *\n * @param filename Filename to check.\n * @return true if prefixed with \"user:\", false otherwise.\n */\n private boolean fileHasUserNamespace(String filename) {\n return filename != null && filename.startsWith(\"user:\");\n }\n\n /**\n * Constructs the blob prefix for an artifact (excluding version).\n *\n * @param appName Application name.\n * @param userId User ID.\n * @param sessionId Session ID.\n * @param filename Artifact filename.\n * @return prefix string for blob location.\n */\n private String getBlobPrefix(String appName, String userId, String sessionId, String filename) {\n if (fileHasUserNamespace(filename)) {\n return String.format(\"%s/%s/user/%s/\", appName, userId, filename);\n } else {\n return String.format(\"%s/%s/%s/%s/\", appName, userId, sessionId, filename);\n }\n }\n\n /**\n * Constructs the full blob name for an artifact, including version.\n *\n * @param appName Application name.\n * @param userId User ID.\n * @param sessionId Session ID.\n * @param filename Artifact filename.\n * @param version Artifact version.\n * @return full blob name.\n */\n private String getBlobName(\n String appName, String userId, String sessionId, String filename, int version) {\n return getBlobPrefix(appName, userId, sessionId, filename) + version;\n }\n\n /**\n * Saves an artifact to GCS and assigns a new version.\n *\n * @param appName Application name.\n * @param userId User ID.\n * @param sessionId Session ID.\n * @param filename Artifact filename.\n * @param artifact Artifact content to save.\n * @return Single with assigned version number.\n */\n @Override\n public Single saveArtifact(\n String appName, String userId, String sessionId, String filename, Part artifact) {\n return listVersions(appName, userId, sessionId, filename)\n .map(versions -> versions.isEmpty() ? 0 : max(versions) + 1)\n .map(\n nextVersion -> {\n String blobName = getBlobName(appName, userId, sessionId, filename, nextVersion);\n BlobId blobId = BlobId.of(bucketName, blobName);\n\n BlobInfo blobInfo =\n BlobInfo.newBuilder(blobId)\n .setContentType(artifact.inlineData().get().mimeType().orElse(null))\n .build();\n\n try {\n byte[] dataToSave =\n artifact\n .inlineData()\n .get()\n .data()\n .orElseThrow(\n () ->\n new IllegalArgumentException(\n \"Saveable artifact data must be non-empty.\"));\n storageClient.create(blobInfo, dataToSave);\n return nextVersion;\n } catch (StorageException e) {\n throw new VerifyException(\"Failed to save artifact to GCS\", e);\n }\n });\n }\n\n /**\n * Loads an artifact from GCS.\n *\n * @param appName Application name.\n * @param userId User ID.\n * @param sessionId Session ID.\n * @param filename Artifact filename.\n * @param version Optional version to load. Loads latest if empty.\n * @return Maybe with loaded artifact, or empty if not found.\n */\n @Override\n public Maybe loadArtifact(\n String appName, String userId, String sessionId, String filename, Optional version) {\n return version\n .map(Maybe::just)\n .orElseGet(\n () ->\n listVersions(appName, userId, sessionId, filename)\n .flatMapMaybe(\n versions -> versions.isEmpty() ? Maybe.empty() : Maybe.just(max(versions))))\n .flatMap(\n versionToLoad -> {\n String blobName = getBlobName(appName, userId, sessionId, filename, versionToLoad);\n BlobId blobId = BlobId.of(bucketName, blobName);\n\n try {\n Blob blob = storageClient.get(blobId);\n if (blob == null || !blob.exists()) {\n return Maybe.empty();\n }\n byte[] data = blob.getContent();\n String mimeType = blob.getContentType();\n return Maybe.just(Part.fromBytes(data, mimeType));\n } catch (StorageException e) {\n return Maybe.empty();\n }\n });\n }\n\n /**\n * Lists artifact filenames for a user and session.\n *\n * @param appName Application name.\n * @param userId User ID.\n * @param sessionId Session ID.\n * @return Single with sorted list of artifact filenames.\n */\n @Override\n public Single listArtifactKeys(\n String appName, String userId, String sessionId) {\n Set filenames = new HashSet<>();\n\n // List session-specific files\n String sessionPrefix = String.format(\"%s/%s/%s/\", appName, userId, sessionId);\n try {\n for (Blob blob :\n storageClient.list(bucketName, BlobListOption.prefix(sessionPrefix)).iterateAll()) {\n List parts = Splitter.on('/').splitToList(blob.getName());\n filenames.add(parts.get(3)); // appName/userId/sessionId/filename/version\n }\n } catch (StorageException e) {\n throw new VerifyException(\"Failed to list session artifacts from GCS\", e);\n }\n\n // List user-namespace files\n String userPrefix = String.format(\"%s/%s/user/\", appName, userId);\n try {\n for (Blob blob :\n storageClient.list(bucketName, BlobListOption.prefix(userPrefix)).iterateAll()) {\n List parts = Splitter.on('/').splitToList(blob.getName());\n filenames.add(parts.get(3)); // appName/userId/user/filename/version\n }\n } catch (StorageException e) {\n throw new VerifyException(\"Failed to list user artifacts from GCS\", e);\n }\n\n return Single.just(\n ListArtifactsResponse.builder().filenames(ImmutableList.sortedCopyOf(filenames)).build());\n }\n\n /**\n * Deletes all versions of the specified artifact from GCS.\n *\n * @param appName Application name.\n * @param userId User ID.\n * @param sessionId Session ID.\n * @param filename Artifact filename.\n * @return Completable indicating operation completion.\n */\n @Override\n public Completable deleteArtifact(\n String appName, String userId, String sessionId, String filename) {\n ImmutableList versions =\n listVersions(appName, userId, sessionId, filename).blockingGet();\n List blobIdsToDelete = new ArrayList<>();\n for (int version : versions) {\n String blobName = getBlobName(appName, userId, sessionId, filename, version);\n blobIdsToDelete.add(BlobId.of(bucketName, blobName));\n }\n\n if (!blobIdsToDelete.isEmpty()) {\n try {\n var unused = storageClient.delete(blobIdsToDelete);\n } catch (StorageException e) {\n throw new VerifyException(\"Failed to delete artifact versions from GCS\", e);\n }\n }\n return Completable.complete();\n }\n\n /**\n * Lists all available versions for a given artifact.\n *\n * @param appName Application name.\n * @param userId User ID.\n * @param sessionId Session ID.\n * @param filename Artifact filename.\n * @return Single with sorted list of version numbers.\n */\n @Override\n public Single> listVersions(\n String appName, String userId, String sessionId, String filename) {\n String prefix = getBlobPrefix(appName, userId, sessionId, filename);\n List versions = new ArrayList<>();\n try {\n for (Blob blob : storageClient.list(bucketName, BlobListOption.prefix(prefix)).iterateAll()) {\n String name = blob.getName();\n int versionDelimiterIndex = name.lastIndexOf('/'); // immediately before the version number\n if (versionDelimiterIndex != -1 && versionDelimiterIndex < name.length() - 1) {\n versions.add(Integer.parseInt(name.substring(versionDelimiterIndex + 1)));\n }\n }\n return Single.just(ImmutableList.sortedCopyOf(versions));\n } catch (StorageException e) {\n return Single.just(ImmutableList.of());\n }\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/llmflows/Contents.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows.llmflows;\n\nimport static com.google.common.collect.ImmutableList.toImmutableList;\n\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.google.adk.JsonBaseModel;\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.agents.LlmAgent;\nimport com.google.adk.events.Event;\nimport com.google.adk.models.LlmRequest;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Iterables;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.FunctionCall;\nimport com.google.genai.types.FunctionResponse;\nimport com.google.genai.types.Part;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.Set;\n\n/** {@link RequestProcessor} that populates content in request for LLM flows. */\npublic final class Contents implements RequestProcessor {\n public Contents() {}\n\n @Override\n public Single processRequest(\n InvocationContext context, LlmRequest request) {\n if (!(context.agent() instanceof LlmAgent)) {\n return Single.just(\n RequestProcessor.RequestProcessingResult.create(request, context.session().events()));\n }\n LlmAgent llmAgent = (LlmAgent) context.agent();\n\n if (llmAgent.includeContents() == LlmAgent.IncludeContents.NONE) {\n return Single.just(\n RequestProcessor.RequestProcessingResult.create(\n request.toBuilder().contents(ImmutableList.of()).build(), ImmutableList.of()));\n }\n\n ImmutableList contents =\n getContents(context.branch(), context.session().events(), context.agent().name());\n\n return Single.just(\n RequestProcessor.RequestProcessingResult.create(\n request.toBuilder().contents(contents).build(), ImmutableList.of()));\n }\n\n private ImmutableList getContents(\n Optional currentBranch, List events, String agentName) {\n List filteredEvents = new ArrayList<>();\n\n // Filter the events, leaving the contents and the function calls and responses from the current\n // agent.\n for (Event event : events) {\n // Skip events without content, or generated neither by user nor by model or has empty text.\n // E.g. events purely for mutating session states.\n if (event.content().isEmpty()) {\n continue;\n }\n var content = event.content().get();\n if (content.role().isEmpty()\n || content.role().get().isEmpty()\n || content.parts().isEmpty()\n || content.parts().get().isEmpty()\n || content.parts().get().get(0).text().map(String::isEmpty).orElse(false)) {\n continue;\n }\n\n if (!isEventBelongsToBranch(currentBranch, event)) {\n continue;\n }\n\n // TODO: Skip auth events.\n\n if (isOtherAgentReply(agentName, event)) {\n filteredEvents.add(convertForeignEvent(event));\n } else {\n filteredEvents.add(event);\n }\n }\n\n List resultEvents = rearrangeEventsForLatestFunctionResponse(filteredEvents);\n resultEvents = rearrangeEventsForAsyncFunctionResponsesInHistory(resultEvents);\n\n return resultEvents.stream()\n .map(Event::content)\n .flatMap(Optional::stream)\n .collect(toImmutableList());\n }\n\n /** Whether the event is a reply from another agent. */\n private static boolean isOtherAgentReply(String agentName, Event event) {\n return !agentName.isEmpty()\n && !event.author().equals(agentName)\n && !event.author().equals(\"user\");\n }\n\n /** Converts an {@code event} authored by another agent to a 'contextual-only' event. */\n private static Event convertForeignEvent(Event event) {\n if (event.content().isEmpty()\n || event.content().get().parts().isEmpty()\n || event.content().get().parts().get().isEmpty()) {\n return event;\n }\n\n List parts = new ArrayList<>();\n parts.add(Part.fromText(\"For context:\"));\n\n String originalAuthor = event.author();\n\n for (Part part : event.content().get().parts().get()) {\n if (part.text().isPresent() && !part.text().get().isEmpty()) {\n parts.add(Part.fromText(String.format(\"[%s] said: %s\", originalAuthor, part.text().get())));\n } else if (part.functionCall().isPresent()) {\n FunctionCall functionCall = part.functionCall().get();\n parts.add(\n Part.fromText(\n String.format(\n \"[%s] called tool `%s` with parameters: %s\",\n originalAuthor,\n functionCall.name().orElse(\"unknown_tool\"),\n functionCall.args().map(Contents::convertMapToJson).orElse(\"{}\"))));\n } else if (part.functionResponse().isPresent()) {\n FunctionResponse functionResponse = part.functionResponse().get();\n parts.add(\n Part.fromText(\n String.format(\n \"[%s] `%s` tool returned result: %s\",\n originalAuthor,\n functionResponse.name().orElse(\"unknown_tool\"),\n functionResponse.response().map(Contents::convertMapToJson).orElse(\"{}\"))));\n } else {\n parts.add(part);\n }\n }\n\n Content content = Content.builder().role(\"user\").parts(parts).build();\n return event.toBuilder().author(\"user\").content(content).build();\n }\n\n private static String convertMapToJson(Map struct) {\n try {\n return JsonBaseModel.getMapper().writeValueAsString(struct);\n } catch (JsonProcessingException e) {\n throw new IllegalStateException(\"Failed to serialize the object to JSON.\", e);\n }\n }\n\n private static boolean isEventBelongsToBranch(Optional invocationBranchOpt, Event event) {\n Optional eventBranchOpt = event.branch();\n\n if (invocationBranchOpt.isEmpty() || invocationBranchOpt.get().isEmpty()) {\n return true;\n }\n if (eventBranchOpt.isEmpty() || eventBranchOpt.get().isEmpty()) {\n return true;\n }\n return invocationBranchOpt.get().startsWith(eventBranchOpt.get());\n }\n\n /**\n * Rearranges the events for the latest function response. If the latest function response is for\n * an async function call, all events between the initial function call and the latest function\n * response will be removed.\n *\n * @param events The list of events.\n * @return A new list of events with the appropriate rearrangement.\n */\n private static List rearrangeEventsForLatestFunctionResponse(List events) {\n // TODO: b/412663475 - Handle parallel function calls within the same event. Currently, this\n // throws an error.\n if (events.isEmpty() || Iterables.getLast(events).functionResponses().isEmpty()) {\n // No need to process if the list is empty or the last event is not a function response\n return events;\n }\n\n Event latestEvent = Iterables.getLast(events);\n // Extract function response IDs from the latest event\n Set functionResponseIds = new HashSet<>();\n latestEvent\n .content()\n .flatMap(Content::parts)\n .ifPresent(\n parts -> {\n for (Part part : parts) {\n part.functionResponse()\n .flatMap(FunctionResponse::id)\n .ifPresent(functionResponseIds::add);\n }\n });\n\n if (functionResponseIds.isEmpty()) {\n return events;\n }\n\n // Check if the second to last event contains the corresponding function call\n if (events.size() >= 2) {\n Event penultimateEvent = events.get(events.size() - 2);\n boolean matchFound =\n penultimateEvent\n .content()\n .flatMap(Content::parts)\n .map(\n parts -> {\n for (Part part : parts) {\n if (part.functionCall()\n .flatMap(FunctionCall::id)\n .map(functionResponseIds::contains)\n .orElse(false)) {\n return true; // Found a matching function call ID\n }\n }\n return false;\n })\n .orElse(false);\n if (matchFound) {\n // The latest function response is already matched with the immediately preceding event\n return events;\n }\n }\n\n // Look for the corresponding function call event by iterating backwards\n int functionCallEventIndex = -1;\n for (int i = events.size() - 3; i >= 0; i--) { // Start from third-to-last\n Event event = events.get(i);\n Optional> partsOptional = event.content().flatMap(Content::parts);\n if (partsOptional.isPresent()) {\n List parts = partsOptional.get();\n for (Part part : parts) {\n Optional callIdOpt = part.functionCall().flatMap(FunctionCall::id);\n if (callIdOpt.isPresent() && functionResponseIds.contains(callIdOpt.get())) {\n functionCallEventIndex = i;\n // Add all function call IDs from this event to the set\n parts.forEach(\n p ->\n p.functionCall().flatMap(FunctionCall::id).ifPresent(functionResponseIds::add));\n break; // Found the matching event\n }\n }\n }\n if (functionCallEventIndex != -1) {\n break; // Exit outer loop once found\n }\n }\n\n if (functionCallEventIndex == -1) {\n if (!functionResponseIds.isEmpty()) {\n throw new IllegalStateException(\n \"No function call event found for function response IDs: \" + functionResponseIds);\n } else {\n return events; // No IDs to match, no rearrangement based on this logic.\n }\n }\n\n List resultEvents = new ArrayList<>(events.subList(0, functionCallEventIndex + 1));\n\n // Collect all function response events between the call and the latest response\n List functionResponseEventsToMerge = new ArrayList<>();\n for (int i = functionCallEventIndex + 1; i < events.size() - 1; i++) {\n Event intermediateEvent = events.get(i);\n boolean hasMatchingResponse =\n intermediateEvent\n .content()\n .flatMap(Content::parts)\n .map(\n parts -> {\n for (Part part : parts) {\n if (part.functionResponse()\n .flatMap(FunctionResponse::id)\n .map(functionResponseIds::contains)\n .orElse(false)) {\n return true;\n }\n }\n return false;\n })\n .orElse(false);\n if (hasMatchingResponse) {\n functionResponseEventsToMerge.add(intermediateEvent);\n }\n }\n functionResponseEventsToMerge.add(latestEvent);\n\n if (!functionResponseEventsToMerge.isEmpty()) {\n resultEvents.add(mergeFunctionResponseEvents(functionResponseEventsToMerge));\n }\n\n return resultEvents;\n }\n\n private static List rearrangeEventsForAsyncFunctionResponsesInHistory(List events) {\n Map functionCallIdToResponseEventIndex = new HashMap<>();\n for (int i = 0; i < events.size(); i++) {\n final int index = i;\n Event event = events.get(index);\n event\n .content()\n .flatMap(Content::parts)\n .ifPresent(\n parts -> {\n for (Part part : parts) {\n part.functionResponse()\n .ifPresent(\n response ->\n response\n .id()\n .ifPresent(\n functionCallId ->\n functionCallIdToResponseEventIndex.put(\n functionCallId, index)));\n }\n });\n }\n\n List resultEvents = new ArrayList<>();\n // Keep track of response events already added to avoid duplicates when merging\n Set processedResponseIndices = new HashSet<>();\n\n for (int i = 0; i < events.size(); i++) {\n Event event = events.get(i);\n\n // Skip response events that have already been processed and added alongside their call event\n if (processedResponseIndices.contains(i)) {\n continue;\n }\n\n Optional> partsOptional = event.content().flatMap(Content::parts);\n boolean hasFunctionCalls =\n partsOptional\n .map(parts -> parts.stream().anyMatch(p -> p.functionCall().isPresent()))\n .orElse(false);\n\n if (hasFunctionCalls) {\n Set responseEventIndices = new HashSet<>();\n // Iterate through parts again to get function call IDs\n partsOptional\n .get()\n .forEach(\n part ->\n part.functionCall()\n .ifPresent(\n call ->\n call.id()\n .ifPresent(\n functionCallId -> {\n if (functionCallIdToResponseEventIndex.containsKey(\n functionCallId)) {\n responseEventIndices.add(\n functionCallIdToResponseEventIndex.get(\n functionCallId));\n }\n })));\n\n resultEvents.add(event); // Add the function call event\n\n if (!responseEventIndices.isEmpty()) {\n List responseEventsToAdd = new ArrayList<>();\n List sortedIndices = new ArrayList<>(responseEventIndices);\n Collections.sort(sortedIndices); // Process in chronological order\n\n for (int index : sortedIndices) {\n if (processedResponseIndices.add(index)) { // Add index and check if it was newly added\n responseEventsToAdd.add(events.get(index));\n }\n }\n\n if (responseEventsToAdd.size() == 1) {\n resultEvents.add(responseEventsToAdd.get(0));\n } else if (responseEventsToAdd.size() > 1) {\n resultEvents.add(mergeFunctionResponseEvents(responseEventsToAdd));\n }\n }\n } else {\n resultEvents.add(event);\n }\n }\n\n return resultEvents;\n }\n\n /**\n * Merges a list of function response events into one event.\n *\n *

The key goal is to ensure: 1. functionCall and functionResponse are always of the same\n * number. 2. The functionCall and functionResponse are consecutively in the content.\n *\n * @param functionResponseEvents A list of function response events. NOTE: functionResponseEvents\n * must fulfill these requirements: 1. The list is in increasing order of timestamp; 2. the\n * first event is the initial function response event; 3. all later events should contain at\n * least one function response part that related to the function call event. Caveat: This\n * implementation doesn't support when a parallel function call event contains async function\n * call of the same name.\n * @return A merged event, that is 1. All later function_response will replace function response\n * part in the initial function response event. 2. All non-function response parts will be\n * appended to the part list of the initial function response event.\n */\n private static Event mergeFunctionResponseEvents(List functionResponseEvents) {\n if (functionResponseEvents.isEmpty()) {\n throw new IllegalArgumentException(\"At least one functionResponse event is required.\");\n }\n if (functionResponseEvents.size() == 1) {\n return functionResponseEvents.get(0);\n }\n\n Event baseEvent = functionResponseEvents.get(0);\n Content baseContent =\n baseEvent\n .content()\n .orElseThrow(() -> new IllegalArgumentException(\"Base event must have content.\"));\n List baseParts =\n baseContent\n .parts()\n .orElseThrow(() -> new IllegalArgumentException(\"Base event content must have parts.\"));\n\n if (baseParts.isEmpty()) {\n throw new IllegalArgumentException(\n \"There should be at least one functionResponse part in the base event.\");\n }\n List partsInMergedEvent = new ArrayList<>(baseParts);\n\n Map partIndicesInMergedEvent = new HashMap<>();\n for (int i = 0; i < partsInMergedEvent.size(); i++) {\n final int index = i;\n Part part = partsInMergedEvent.get(i);\n if (part.functionResponse().isPresent()) {\n part.functionResponse()\n .get()\n .id()\n .ifPresent(functionCallId -> partIndicesInMergedEvent.put(functionCallId, index));\n }\n }\n\n for (Event event : functionResponseEvents.subList(1, functionResponseEvents.size())) {\n if (!hasContentWithNonEmptyParts(event)) {\n continue;\n }\n\n for (Part part : event.content().get().parts().get()) {\n if (part.functionResponse().isPresent()) {\n Optional functionCallIdOpt = part.functionResponse().get().id();\n if (functionCallIdOpt.isPresent()) {\n String functionCallId = functionCallIdOpt.get();\n if (partIndicesInMergedEvent.containsKey(functionCallId)) {\n partsInMergedEvent.set(partIndicesInMergedEvent.get(functionCallId), part);\n } else {\n partsInMergedEvent.add(part);\n partIndicesInMergedEvent.put(functionCallId, partsInMergedEvent.size() - 1);\n }\n } else {\n partsInMergedEvent.add(part);\n }\n } else {\n partsInMergedEvent.add(part);\n }\n }\n }\n\n return baseEvent.toBuilder()\n .content(\n Optional.of(\n Content.builder().role(baseContent.role().get()).parts(partsInMergedEvent).build()))\n .build();\n }\n\n private static boolean hasContentWithNonEmptyParts(Event event) {\n return event\n .content() // Optional\n .flatMap(Content::parts) // Optional>\n .map(list -> !list.isEmpty()) // Optional\n .orElse(false);\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/models/GeminiLlmConnection.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.models;\n\nimport static com.google.common.collect.ImmutableList.toImmutableList;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.genai.AsyncSession;\nimport com.google.genai.Client;\nimport com.google.genai.types.Blob;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.FinishReason;\nimport com.google.genai.types.FunctionCall;\nimport com.google.genai.types.FunctionResponse;\nimport com.google.genai.types.LiveConnectConfig;\nimport com.google.genai.types.LiveSendClientContentParameters;\nimport com.google.genai.types.LiveSendRealtimeInputParameters;\nimport com.google.genai.types.LiveSendToolResponseParameters;\nimport com.google.genai.types.LiveServerContent;\nimport com.google.genai.types.LiveServerMessage;\nimport com.google.genai.types.LiveServerToolCall;\nimport com.google.genai.types.Part;\nimport io.reactivex.rxjava3.core.Completable;\nimport io.reactivex.rxjava3.core.Flowable;\nimport io.reactivex.rxjava3.processors.PublishProcessor;\nimport java.net.SocketException;\nimport java.util.List;\nimport java.util.Objects;\nimport java.util.Optional;\nimport java.util.concurrent.CompletableFuture;\nimport java.util.concurrent.CompletionException;\nimport java.util.concurrent.atomic.AtomicBoolean;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * Manages a persistent, bidirectional connection to the Gemini model via WebSockets for real-time\n * interaction.\n *\n *

This connection allows sending conversation history, individual messages, function responses,\n * and real-time media blobs (like audio chunks) while continuously receiving responses from the\n * model.\n */\npublic final class GeminiLlmConnection implements BaseLlmConnection {\n\n private static final Logger logger = LoggerFactory.getLogger(GeminiLlmConnection.class);\n\n private final Client apiClient;\n private final String modelName;\n private final LiveConnectConfig connectConfig;\n private final CompletableFuture sessionFuture;\n private final PublishProcessor responseProcessor = PublishProcessor.create();\n private final Flowable responseFlowable = responseProcessor.serialize();\n private final AtomicBoolean closed = new AtomicBoolean(false);\n\n /**\n * Establishes a new connection.\n *\n * @param apiClient The API client for communication.\n * @param modelName The specific Gemini model endpoint (e.g., \"gemini-2.0-flash).\n * @param connectConfig Configuration parameters for the live session.\n */\n GeminiLlmConnection(Client apiClient, String modelName, LiveConnectConfig connectConfig) {\n this.apiClient = Objects.requireNonNull(apiClient);\n this.modelName = Objects.requireNonNull(modelName);\n this.connectConfig = Objects.requireNonNull(connectConfig);\n\n this.sessionFuture =\n this.apiClient\n .async\n .live\n .connect(this.modelName, this.connectConfig)\n .whenCompleteAsync(\n (session, throwable) -> {\n if (throwable != null) {\n handleConnectionError(throwable);\n } else if (session != null) {\n setupReceiver(session);\n } else if (!closed.get()) {\n handleConnectionError(\n new SocketException(\"WebSocket connection failed without explicit error.\"));\n }\n });\n }\n\n /** Configures the session to forward incoming messages to the response processor. */\n private void setupReceiver(AsyncSession session) {\n if (closed.get()) {\n closeSessionIgnoringErrors(session);\n return;\n }\n session\n .receive(this::handleServerMessage)\n .exceptionally(\n error -> {\n handleReceiveError(error);\n return null;\n });\n }\n\n /** Processes messages received from the WebSocket server. */\n private void handleServerMessage(LiveServerMessage message) {\n if (closed.get()) {\n return;\n }\n\n logger.debug(\"Received server message: {}\", message.toJson());\n\n Optional llmResponse = convertToServerResponse(message);\n llmResponse.ifPresent(responseProcessor::onNext);\n }\n\n /** Converts a server message into the standardized LlmResponse format. */\n private Optional convertToServerResponse(LiveServerMessage message) {\n LlmResponse.Builder builder = LlmResponse.builder();\n\n if (message.serverContent().isPresent()) {\n LiveServerContent serverContent = message.serverContent().get();\n serverContent.modelTurn().ifPresent(builder::content);\n builder\n .partial(serverContent.turnComplete().map(completed -> !completed).orElse(false))\n .turnComplete(serverContent.turnComplete().orElse(false));\n } else if (message.toolCall().isPresent()) {\n LiveServerToolCall toolCall = message.toolCall().get();\n toolCall\n .functionCalls()\n .ifPresent(\n calls -> {\n for (FunctionCall call : calls) {\n builder.content(\n Content.builder()\n .parts(ImmutableList.of(Part.builder().functionCall(call).build()))\n .build());\n }\n });\n builder.partial(false).turnComplete(false);\n } else if (message.usageMetadata().isPresent()) {\n logger.debug(\"Received usage metadata: {}\", message.usageMetadata().get());\n return Optional.empty();\n } else if (message.toolCallCancellation().isPresent()) {\n logger.debug(\"Received tool call cancellation: {}\", message.toolCallCancellation().get());\n // TODO: implement proper CFC and thus tool call cancellation handling.\n return Optional.empty();\n } else if (message.setupComplete().isPresent()) {\n logger.debug(\"Received setup complete.\");\n return Optional.empty();\n } else {\n logger.warn(\"Received unknown or empty server message: {}\", message.toJson());\n builder\n .errorCode(new FinishReason(\"Unknown server message.\"))\n .errorMessage(\"Received unknown server message.\");\n }\n\n return Optional.of(builder.build());\n }\n\n /** Handles errors that occur *during* the initial connection attempt. */\n private void handleConnectionError(Throwable throwable) {\n if (closed.compareAndSet(false, true)) {\n logger.error(\"WebSocket connection failed\", throwable);\n Throwable cause =\n (throwable instanceof CompletionException) ? throwable.getCause() : throwable;\n responseProcessor.onError(cause);\n }\n }\n\n /** Handles errors reported by the WebSocket client *after* connection (e.g., receive errors). */\n private void handleReceiveError(Throwable throwable) {\n if (closed.compareAndSet(false, true)) {\n logger.error(\"Error during WebSocket receive operation\", throwable);\n responseProcessor.onError(throwable);\n sessionFuture.thenAccept(this::closeSessionIgnoringErrors).exceptionally(err -> null);\n }\n }\n\n @Override\n public Completable sendHistory(List history) {\n return sendClientContentInternal(\n LiveSendClientContentParameters.builder().turns(history).build());\n }\n\n @Override\n public Completable sendContent(Content content) {\n Objects.requireNonNull(content, \"content cannot be null\");\n\n Optional> functionResponses = extractFunctionResponses(content);\n\n if (functionResponses.isPresent()) {\n return sendToolResponseInternal(\n LiveSendToolResponseParameters.builder()\n .functionResponses(functionResponses.get())\n .build());\n } else {\n return sendClientContentInternal(\n LiveSendClientContentParameters.builder().turns(ImmutableList.of(content)).build());\n }\n }\n\n /** Extracts FunctionResponse parts from a Content object if all parts are FunctionResponses. */\n private Optional> extractFunctionResponses(Content content) {\n if (content.parts().isEmpty() || content.parts().get().isEmpty()) {\n return Optional.empty();\n }\n\n ImmutableList responses =\n content.parts().get().stream()\n .map(Part::functionResponse)\n .flatMap(Optional::stream)\n .collect(toImmutableList());\n\n // Ensure *all* parts were function responses\n if (responses.size() == content.parts().get().size()) {\n return Optional.of(responses);\n } else {\n return Optional.empty();\n }\n }\n\n @Override\n public Completable sendRealtime(Blob blob) {\n return Completable.fromFuture(\n sessionFuture.thenCompose(\n session ->\n session.sendRealtimeInput(\n LiveSendRealtimeInputParameters.builder().media(blob).build())));\n }\n\n /** Helper to send client content parameters. */\n private Completable sendClientContentInternal(LiveSendClientContentParameters parameters) {\n return Completable.fromFuture(\n sessionFuture.thenCompose(session -> session.sendClientContent(parameters)));\n }\n\n /** Helper to send tool response parameters. */\n private Completable sendToolResponseInternal(LiveSendToolResponseParameters parameters) {\n return Completable.fromFuture(\n sessionFuture.thenCompose(session -> session.sendToolResponse(parameters)));\n }\n\n @Override\n public Flowable receive() {\n return responseFlowable;\n }\n\n @Override\n public void close() {\n closeInternal(null);\n }\n\n @Override\n public void close(Throwable throwable) {\n Objects.requireNonNull(throwable, \"throwable cannot be null for close\");\n closeInternal(throwable);\n }\n\n /** Internal method to handle closing logic and signal completion/error. */\n private void closeInternal(Throwable throwable) {\n if (closed.compareAndSet(false, true)) {\n logger.debug(\"Closing GeminiConnection.\", throwable);\n\n if (throwable == null) {\n responseProcessor.onComplete();\n } else {\n responseProcessor.onError(throwable);\n }\n\n if (sessionFuture.isDone()) {\n sessionFuture.thenAccept(this::closeSessionIgnoringErrors).exceptionally(err -> null);\n } else {\n sessionFuture.cancel(false);\n }\n }\n }\n\n /** Closes the AsyncSession safely, logging any errors. */\n private void closeSessionIgnoringErrors(AsyncSession session) {\n if (session != null) {\n session\n .close()\n .exceptionally(\n closeError -> {\n logger.warn(\"Error occurred while closing AsyncSession\", closeError);\n return null; // Suppress error during close\n });\n }\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/models/Gemini.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.models;\n\nimport static com.google.common.base.StandardSystemProperty.JAVA_VERSION;\nimport static com.google.common.collect.ImmutableList.toImmutableList;\n\nimport com.google.adk.Version;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport com.google.genai.Client;\nimport com.google.genai.ResponseStream;\nimport com.google.genai.types.Blob;\nimport com.google.genai.types.Candidate;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.FileData;\nimport com.google.genai.types.FinishReason;\nimport com.google.genai.types.GenerateContentConfig;\nimport com.google.genai.types.GenerateContentResponse;\nimport com.google.genai.types.HttpOptions;\nimport com.google.genai.types.LiveConnectConfig;\nimport com.google.genai.types.Part;\nimport io.reactivex.rxjava3.core.Flowable;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Objects;\nimport java.util.Optional;\nimport java.util.concurrent.CompletableFuture;\nimport java.util.stream.Stream;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * Represents the Gemini Generative AI model.\n *\n *

This class provides methods for interacting with the Gemini model, including standard\n * request-response generation and establishing persistent bidirectional connections.\n */\npublic class Gemini extends BaseLlm {\n\n private static final Logger logger = LoggerFactory.getLogger(Gemini.class);\n private static final ImmutableMap TRACKING_HEADERS;\n\n static {\n String frameworkLabel = \"google-adk/\" + Version.JAVA_ADK_VERSION;\n String languageLabel = \"gl-java/\" + JAVA_VERSION.value();\n String versionHeaderValue = String.format(\"%s %s\", frameworkLabel, languageLabel);\n\n TRACKING_HEADERS =\n ImmutableMap.of(\n \"x-goog-api-client\", versionHeaderValue,\n \"user-agent\", versionHeaderValue);\n }\n\n private final Client apiClient;\n\n private static final String CONTINUE_OUTPUT_MESSAGE =\n \"Continue output. DO NOT look at this line. ONLY look at the content before this line and\"\n + \" system instruction.\";\n\n /**\n * Constructs a new Gemini instance.\n *\n * @param modelName The name of the Gemini model to use (e.g., \"gemini-2.0-flash\").\n * @param apiClient The genai {@link com.google.genai.Client} instance for making API calls.\n */\n public Gemini(String modelName, Client apiClient) {\n super(modelName);\n this.apiClient = Objects.requireNonNull(apiClient, \"apiClient cannot be null\");\n }\n\n /**\n * Constructs a new Gemini instance with a Google Gemini API key.\n *\n * @param modelName The name of the Gemini model to use (e.g., \"gemini-2.0-flash\").\n * @param apiKey The Google Gemini API key.\n */\n public Gemini(String modelName, String apiKey) {\n super(modelName);\n Objects.requireNonNull(apiKey, \"apiKey cannot be null\");\n this.apiClient =\n Client.builder()\n .apiKey(apiKey)\n .httpOptions(HttpOptions.builder().headers(TRACKING_HEADERS).build())\n .build();\n }\n\n /**\n * Constructs a new Gemini instance with a Google Gemini API key.\n *\n * @param modelName The name of the Gemini model to use (e.g., \"gemini-2.0-flash\").\n * @param vertexCredentials The Vertex AI credentials to access the Gemini model.\n */\n public Gemini(String modelName, VertexCredentials vertexCredentials) {\n super(modelName);\n Objects.requireNonNull(vertexCredentials, \"vertexCredentials cannot be null\");\n Client.Builder apiClientBuilder =\n Client.builder().httpOptions(HttpOptions.builder().headers(TRACKING_HEADERS).build());\n vertexCredentials.project().ifPresent(apiClientBuilder::project);\n vertexCredentials.location().ifPresent(apiClientBuilder::location);\n vertexCredentials.credentials().ifPresent(apiClientBuilder::credentials);\n this.apiClient = apiClientBuilder.build();\n }\n\n /**\n * Returns a new Builder instance for constructing Gemini objects. Note that when building a\n * Gemini object, at least one of apiKey, vertexCredentials, or an explicit apiClient must be set.\n * If multiple are set, the explicit apiClient will take precedence.\n *\n * @return A new {@link Builder}.\n */\n public static Builder builder() {\n return new Builder();\n }\n\n /** Builder for {@link Gemini}. */\n public static class Builder {\n private String modelName;\n private Client apiClient;\n private String apiKey;\n private VertexCredentials vertexCredentials;\n\n private Builder() {}\n\n /**\n * Sets the name of the Gemini model to use.\n *\n * @param modelName The model name (e.g., \"gemini-2.0-flash\").\n * @return This builder.\n */\n @CanIgnoreReturnValue\n public Builder modelName(String modelName) {\n this.modelName = modelName;\n return this;\n }\n\n /**\n * Sets the explicit {@link com.google.genai.Client} instance for making API calls. If this is\n * set, apiKey and vertexCredentials will be ignored.\n *\n * @param apiClient The client instance.\n * @return This builder.\n */\n @CanIgnoreReturnValue\n public Builder apiClient(Client apiClient) {\n this.apiClient = apiClient;\n return this;\n }\n\n /**\n * Sets the Google Gemini API key. If {@link #apiClient(Client)} is also set, the explicit\n * client will take precedence. If {@link #vertexCredentials(VertexCredentials)} is also set,\n * this apiKey will take precedence.\n *\n * @param apiKey The API key.\n * @return This builder.\n */\n @CanIgnoreReturnValue\n public Builder apiKey(String apiKey) {\n this.apiKey = apiKey;\n return this;\n }\n\n /**\n * Sets the Vertex AI credentials. If {@link #apiClient(Client)} or {@link #apiKey(String)} are\n * also set, they will take precedence over these credentials.\n *\n * @param vertexCredentials The Vertex AI credentials.\n * @return This builder.\n */\n @CanIgnoreReturnValue\n public Builder vertexCredentials(VertexCredentials vertexCredentials) {\n this.vertexCredentials = vertexCredentials;\n return this;\n }\n\n /**\n * Builds the {@link Gemini} instance.\n *\n * @return A new {@link Gemini} instance.\n * @throws NullPointerException if modelName is null.\n */\n public Gemini build() {\n Objects.requireNonNull(modelName, \"modelName must be set.\");\n\n if (apiClient != null) {\n return new Gemini(modelName, apiClient);\n } else if (apiKey != null) {\n return new Gemini(modelName, apiKey);\n } else if (vertexCredentials != null) {\n return new Gemini(modelName, vertexCredentials);\n } else {\n return new Gemini(\n modelName,\n Client.builder()\n .httpOptions(HttpOptions.builder().headers(TRACKING_HEADERS).build())\n .build());\n }\n }\n }\n\n /**\n * Sanitizes the request to ensure it is compatible with the configured API backend. Required as\n * there are some parameters that if included in the request will raise a runtime error if sent to\n * the wrong backend (e.g. image names when the backend isn't Vertex AI).\n *\n * @param llmRequest The request to sanitize.\n * @return The sanitized request.\n */\n private LlmRequest sanitizeRequest(LlmRequest llmRequest) {\n if (apiClient.vertexAI()) {\n return llmRequest;\n }\n LlmRequest.Builder requestBuilder = llmRequest.toBuilder();\n\n // Using API key from Google AI Studio to call model doesn't support labels.\n llmRequest\n .config()\n .ifPresent(\n config -> {\n if (config.labels().isPresent()) {\n requestBuilder.config(config.toBuilder().labels(null).build());\n }\n });\n\n if (llmRequest.contents().isEmpty()) {\n return requestBuilder.build();\n }\n\n // This backend does not support the display_name parameter for file uploads,\n // so it must be removed to prevent request failures.\n ImmutableList updatedContents =\n llmRequest.contents().stream()\n .map(\n content -> {\n if (content.parts().isEmpty() || content.parts().get().isEmpty()) {\n return content;\n }\n\n ImmutableList updatedParts =\n content.parts().get().stream()\n .map(\n part -> {\n Part.Builder partBuilder = part.toBuilder();\n if (part.inlineData().flatMap(Blob::displayName).isPresent()) {\n Blob blob = part.inlineData().get();\n Blob.Builder newBlobBuilder = Blob.builder();\n blob.data().ifPresent(newBlobBuilder::data);\n blob.mimeType().ifPresent(newBlobBuilder::mimeType);\n partBuilder.inlineData(newBlobBuilder.build());\n }\n if (part.fileData().flatMap(FileData::displayName).isPresent()) {\n FileData fileData = part.fileData().get();\n FileData.Builder newFileDataBuilder = FileData.builder();\n fileData.fileUri().ifPresent(newFileDataBuilder::fileUri);\n fileData.mimeType().ifPresent(newFileDataBuilder::mimeType);\n partBuilder.fileData(newFileDataBuilder.build());\n }\n return partBuilder.build();\n })\n .collect(toImmutableList());\n\n return content.toBuilder().parts(updatedParts).build();\n })\n .collect(toImmutableList());\n return requestBuilder.contents(updatedContents).build();\n }\n\n @Override\n public Flowable generateContent(LlmRequest llmRequest, boolean stream) {\n llmRequest = sanitizeRequest(llmRequest);\n List contents = llmRequest.contents();\n // Last content must be from the user, otherwise the model won't respond.\n if (contents.isEmpty() || !Iterables.getLast(contents).role().orElse(\"\").equals(\"user\")) {\n Content userContent = Content.fromParts(Part.fromText(CONTINUE_OUTPUT_MESSAGE));\n contents =\n Stream.concat(contents.stream(), Stream.of(userContent)).collect(toImmutableList());\n }\n\n List finalContents = stripThoughts(contents);\n GenerateContentConfig config = llmRequest.config().orElse(null);\n String effectiveModelName = llmRequest.model().orElse(model());\n\n logger.trace(\"Request Contents: {}\", finalContents);\n logger.trace(\"Request Config: {}\", config);\n\n if (stream) {\n logger.debug(\"Sending streaming generateContent request to model {}\", effectiveModelName);\n CompletableFuture> streamFuture =\n apiClient.async.models.generateContentStream(effectiveModelName, finalContents, config);\n\n return Flowable.defer(\n () -> {\n final StringBuilder accumulatedText = new StringBuilder();\n // Array to bypass final local variable reassignment in lambda.\n final GenerateContentResponse[] lastRawResponseHolder = {null};\n\n return Flowable.fromFuture(streamFuture)\n .flatMapIterable(iterable -> iterable)\n .concatMap(\n rawResponse -> {\n lastRawResponseHolder[0] = rawResponse;\n logger.trace(\"Raw streaming response: {}\", rawResponse);\n\n List responsesToEmit = new ArrayList<>();\n LlmResponse currentProcessedLlmResponse = LlmResponse.create(rawResponse);\n String currentTextChunk = getTextFromLlmResponse(currentProcessedLlmResponse);\n\n if (!currentTextChunk.isEmpty()) {\n accumulatedText.append(currentTextChunk);\n LlmResponse partialResponse =\n currentProcessedLlmResponse.toBuilder().partial(true).build();\n responsesToEmit.add(partialResponse);\n } else {\n if (accumulatedText.length() > 0\n && shouldEmitAccumulatedText(currentProcessedLlmResponse)) {\n LlmResponse aggregatedTextResponse =\n LlmResponse.builder()\n .content(\n Content.builder()\n .parts(\n ImmutableList.of(\n Part.builder()\n .text(accumulatedText.toString())\n .build()))\n .build())\n .build();\n responsesToEmit.add(aggregatedTextResponse);\n accumulatedText.setLength(0);\n }\n responsesToEmit.add(currentProcessedLlmResponse);\n }\n logger.debug(\"Responses to emit: {}\", responsesToEmit);\n return Flowable.fromIterable(responsesToEmit);\n })\n .concatWith(\n Flowable.defer(\n () -> {\n if (accumulatedText.length() > 0 && lastRawResponseHolder[0] != null) {\n GenerateContentResponse finalRawResp = lastRawResponseHolder[0];\n boolean isStop =\n finalRawResp\n .candidates()\n .flatMap(\n candidates ->\n candidates.isEmpty()\n ? Optional.empty()\n : Optional.of(candidates.get(0)))\n .flatMap(Candidate::finishReason)\n .map(\n finishReason ->\n finishReason.equals(\n new FinishReason(FinishReason.Known.STOP)))\n .orElse(false);\n\n if (isStop) {\n LlmResponse finalAggregatedTextResponse =\n LlmResponse.builder()\n .content(\n Content.builder()\n .parts(\n ImmutableList.of(\n Part.builder()\n .text(accumulatedText.toString())\n .build()))\n .build())\n .build();\n return Flowable.just(finalAggregatedTextResponse);\n }\n }\n return Flowable.empty();\n }));\n });\n } else {\n logger.debug(\"Sending generateContent request to model {}\", effectiveModelName);\n return Flowable.fromFuture(\n apiClient\n .async\n .models\n .generateContent(effectiveModelName, finalContents, config)\n .thenApplyAsync(LlmResponse::create));\n }\n }\n\n /**\n * Extracts text content from the first part of an LlmResponse, if available.\n *\n * @param llmResponse The LlmResponse to extract text from.\n * @return The text content, or an empty string if not found.\n */\n private String getTextFromLlmResponse(LlmResponse llmResponse) {\n return llmResponse\n .content()\n .flatMap(Content::parts)\n .filter(parts -> !parts.isEmpty())\n .map(parts -> parts.get(0))\n .flatMap(Part::text)\n .orElse(\"\");\n }\n\n /**\n * Determines if accumulated text should be emitted based on the current LlmResponse. We flush if\n * current response is not a text continuation (e.g., no content, no parts, or the first part is\n * not inline_data, meaning it's something else or just empty, thereby warranting a flush of\n * preceding text).\n *\n * @param currentLlmResponse The current LlmResponse being processed.\n * @return True if accumulated text should be emitted, false otherwise.\n */\n private boolean shouldEmitAccumulatedText(LlmResponse currentLlmResponse) {\n Optional contentOpt = currentLlmResponse.content();\n if (contentOpt.isEmpty()) {\n return true;\n }\n\n Optional> partsOpt = contentOpt.get().parts();\n if (partsOpt.isEmpty() || partsOpt.get().isEmpty()) {\n return true;\n }\n\n // If content and parts are present, and parts list is not empty, we want to yield accumulated\n // text only if `text` is present AND (`not llm_response.content` OR `not\n // llm_response.content.parts` OR `not llm_response.content.parts[0].inline_data`)\n // This means we flush if the first part does NOT have inline_data.\n // If it *has* inline_data, the condition below is false,\n // and we would not flush based on this specific sub-condition.\n Part firstPart = partsOpt.get().get(0);\n return firstPart.inlineData().isEmpty();\n }\n\n @Override\n public BaseLlmConnection connect(LlmRequest llmRequest) {\n llmRequest = sanitizeRequest(llmRequest);\n logger.debug(\"Establishing Gemini connection.\");\n LiveConnectConfig liveConnectConfig = llmRequest.liveConnectConfig();\n String effectiveModelName = llmRequest.model().orElse(model());\n\n logger.debug(\"Connecting to model {}\", effectiveModelName);\n logger.trace(\"Connection Config: {}\", liveConnectConfig);\n\n return new GeminiLlmConnection(apiClient, effectiveModelName, liveConnectConfig);\n }\n\n /** Removes any `Part` that contains only a `thought` from the content list. */\n private List stripThoughts(List originalContents) {\n List updatedContents = new ArrayList<>();\n for (Content content : originalContents) {\n ImmutableList nonThoughtParts =\n content.parts().orElse(ImmutableList.of()).stream()\n // Keep if thought is not present OR if thought is present but false\n .filter(part -> part.thought().map(isThought -> !isThought).orElse(true))\n .collect(toImmutableList());\n updatedContents.add(content.toBuilder().parts(nonThoughtParts).build());\n }\n return updatedContents;\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/llmflows/Functions.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows.llmflows;\n\nimport com.google.adk.Telemetry;\nimport com.google.adk.agents.Callbacks.AfterToolCallback;\nimport com.google.adk.agents.Callbacks.BeforeToolCallback;\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.agents.LlmAgent;\nimport com.google.adk.events.Event;\nimport com.google.adk.events.EventActions;\nimport com.google.adk.tools.BaseTool;\nimport com.google.adk.tools.ToolContext;\nimport com.google.common.base.VerifyException;\nimport com.google.common.collect.ImmutableList;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.FunctionCall;\nimport com.google.genai.types.FunctionResponse;\nimport com.google.genai.types.Part;\nimport io.opentelemetry.api.trace.Span;\nimport io.opentelemetry.api.trace.Tracer;\nimport io.opentelemetry.context.Scope;\nimport io.reactivex.rxjava3.core.Flowable;\nimport io.reactivex.rxjava3.core.Maybe;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.Set;\nimport java.util.UUID;\nimport org.jspecify.annotations.Nullable;\n\n/** Utility class for handling function calls. */\npublic final class Functions {\n\n private static final String AF_FUNCTION_CALL_ID_PREFIX = \"adk-\";\n\n /** Generates a unique ID for a function call. */\n public static String generateClientFunctionCallId() {\n return AF_FUNCTION_CALL_ID_PREFIX + UUID.randomUUID();\n }\n\n /**\n * Populates missing function call IDs in the provided event's content.\n *\n *

If the event contains function calls without an ID, this method generates a unique\n * client-side ID for each and updates the event content.\n *\n * @param modelResponseEvent The event potentially containing function calls.\n */\n public static void populateClientFunctionCallId(Event modelResponseEvent) {\n Optional originalContentOptional = modelResponseEvent.content();\n if (originalContentOptional.isEmpty()) {\n return;\n }\n Content originalContent = originalContentOptional.get();\n List originalParts = originalContent.parts().orElse(ImmutableList.of());\n if (originalParts.stream().noneMatch(part -> part.functionCall().isPresent())) {\n return; // No function calls to process\n }\n\n List newParts = new ArrayList<>();\n boolean modified = false;\n for (Part part : originalParts) {\n if (part.functionCall().isPresent()) {\n FunctionCall functionCall = part.functionCall().get();\n if (functionCall.id().isEmpty() || functionCall.id().get().isEmpty()) {\n FunctionCall updatedFunctionCall =\n functionCall.toBuilder().id(generateClientFunctionCallId()).build();\n newParts.add(Part.builder().functionCall(updatedFunctionCall).build());\n modified = true;\n } else {\n newParts.add(part); // Keep original part if ID exists\n }\n } else {\n newParts.add(part); // Keep non-function call parts\n }\n }\n\n if (modified) {\n String role =\n originalContent\n .role()\n .orElseThrow(\n () ->\n new IllegalStateException(\n \"Content role is missing in event: \" + modelResponseEvent.id()));\n Content newContent = Content.builder().role(role).parts(newParts).build();\n modelResponseEvent.setContent(Optional.of(newContent));\n }\n }\n\n // TODO - b/413761119 add the remaining methods for function call id.\n\n public static Maybe handleFunctionCalls(\n InvocationContext invocationContext, Event functionCallEvent, Map tools) {\n ImmutableList functionCalls = functionCallEvent.functionCalls();\n\n List> functionResponseEvents = new ArrayList<>();\n\n for (FunctionCall functionCall : functionCalls) {\n if (!tools.containsKey(functionCall.name().get())) {\n throw new VerifyException(\"Tool not found: \" + functionCall.name().get());\n }\n BaseTool tool = tools.get(functionCall.name().get());\n ToolContext toolContext =\n ToolContext.builder(invocationContext)\n .functionCallId(functionCall.id().orElse(\"\"))\n .build();\n\n Map functionArgs = functionCall.args().orElse(new HashMap<>());\n\n Maybe> maybeFunctionResult =\n maybeInvokeBeforeToolCall(invocationContext, tool, functionArgs, toolContext)\n .switchIfEmpty(Maybe.defer(() -> callTool(tool, functionArgs, toolContext)));\n\n Maybe maybeFunctionResponseEvent =\n maybeFunctionResult\n .map(Optional::of)\n .defaultIfEmpty(Optional.empty())\n .flatMapMaybe(\n optionalInitialResult -> {\n Map initialFunctionResult = optionalInitialResult.orElse(null);\n\n Maybe> afterToolResultMaybe =\n maybeInvokeAfterToolCall(\n invocationContext,\n tool,\n functionArgs,\n toolContext,\n initialFunctionResult);\n\n return afterToolResultMaybe\n .map(Optional::of)\n .defaultIfEmpty(Optional.ofNullable(initialFunctionResult))\n .flatMapMaybe(\n finalOptionalResult -> {\n Map finalFunctionResult =\n finalOptionalResult.orElse(null);\n if (tool.longRunning() && finalFunctionResult == null) {\n return Maybe.empty();\n }\n Event functionResponseEvent =\n buildResponseEvent(\n tool, finalFunctionResult, toolContext, invocationContext);\n return Maybe.just(functionResponseEvent);\n });\n });\n\n functionResponseEvents.add(maybeFunctionResponseEvent);\n }\n\n return Maybe.merge(functionResponseEvents)\n .toList()\n .flatMapMaybe(\n events -> {\n if (events.isEmpty()) {\n return Maybe.empty();\n }\n Event mergedEvent = Functions.mergeParallelFunctionResponseEvents(events);\n if (mergedEvent == null) {\n return Maybe.empty();\n }\n\n if (events.size() > 1) {\n Tracer tracer = Telemetry.getTracer();\n Span mergedSpan = tracer.spanBuilder(\"tool_response\").startSpan();\n try (Scope scope = mergedSpan.makeCurrent()) {\n Telemetry.traceToolResponse(invocationContext, mergedEvent.id(), mergedEvent);\n } finally {\n mergedSpan.end();\n }\n }\n return Maybe.just(mergedEvent);\n });\n }\n\n public static Set getLongRunningFunctionCalls(\n List functionCalls, Map tools) {\n Set longRunningFunctionCalls = new HashSet<>();\n for (FunctionCall functionCall : functionCalls) {\n if (!tools.containsKey(functionCall.name().get())) {\n continue;\n }\n BaseTool tool = tools.get(functionCall.name().get());\n if (tool.longRunning()) {\n longRunningFunctionCalls.add(functionCall.id().orElse(\"\"));\n }\n }\n return longRunningFunctionCalls;\n }\n\n private static @Nullable Event mergeParallelFunctionResponseEvents(\n List functionResponseEvents) {\n if (functionResponseEvents.isEmpty()) {\n return null;\n }\n if (functionResponseEvents.size() == 1) {\n return functionResponseEvents.get(0);\n }\n // Use the first event as the base for common attributes\n Event baseEvent = functionResponseEvents.get(0);\n\n List mergedParts = new ArrayList<>();\n for (Event event : functionResponseEvents) {\n event.content().flatMap(Content::parts).ifPresent(mergedParts::addAll);\n }\n\n // Merge actions from all events\n // TODO: validate that pending actions are not cleared away\n EventActions.Builder mergedActionsBuilder = EventActions.builder();\n for (Event event : functionResponseEvents) {\n mergedActionsBuilder.merge(event.actions());\n }\n\n return Event.builder()\n .id(Event.generateEventId())\n .invocationId(baseEvent.invocationId())\n .author(baseEvent.author())\n .branch(baseEvent.branch())\n .content(Optional.of(Content.builder().role(\"user\").parts(mergedParts).build()))\n .actions(mergedActionsBuilder.build())\n .timestamp(baseEvent.timestamp())\n .build();\n }\n\n private static Maybe> maybeInvokeBeforeToolCall(\n InvocationContext invocationContext,\n BaseTool tool,\n Map functionArgs,\n ToolContext toolContext) {\n if (invocationContext.agent() instanceof LlmAgent) {\n LlmAgent agent = (LlmAgent) invocationContext.agent();\n\n Optional> callbacksOpt = agent.beforeToolCallback();\n if (callbacksOpt.isEmpty() || callbacksOpt.get().isEmpty()) {\n return Maybe.empty();\n }\n List callbacks = callbacksOpt.get();\n\n return Flowable.fromIterable(callbacks)\n .concatMapMaybe(\n callback -> callback.call(invocationContext, tool, functionArgs, toolContext))\n .firstElement();\n }\n return Maybe.empty();\n }\n\n private static Maybe> maybeInvokeAfterToolCall(\n InvocationContext invocationContext,\n BaseTool tool,\n Map functionArgs,\n ToolContext toolContext,\n Map functionResult) {\n if (invocationContext.agent() instanceof LlmAgent) {\n LlmAgent agent = (LlmAgent) invocationContext.agent();\n Optional> callbacksOpt = agent.afterToolCallback();\n if (callbacksOpt.isEmpty() || callbacksOpt.get().isEmpty()) {\n return Maybe.empty();\n }\n List callbacks = callbacksOpt.get();\n\n return Flowable.fromIterable(callbacks)\n .concatMapMaybe(\n callback ->\n callback.call(invocationContext, tool, functionArgs, toolContext, functionResult))\n .firstElement();\n }\n return Maybe.empty();\n }\n\n private static Maybe> callTool(\n BaseTool tool, Map args, ToolContext toolContext) {\n Tracer tracer = Telemetry.getTracer();\n return Maybe.defer(\n () -> {\n Span span = tracer.spanBuilder(\"tool_call [\" + tool.name() + \"]\").startSpan();\n try (Scope scope = span.makeCurrent()) {\n Telemetry.traceToolCall(args);\n return tool.runAsync(args, toolContext)\n .toMaybe()\n .doOnError(span::recordException)\n .doFinally(span::end);\n } catch (RuntimeException e) {\n span.recordException(e);\n span.end();\n return Maybe.error(new RuntimeException(\"Failed to call tool: \" + tool.name(), e));\n }\n });\n }\n\n private static Event buildResponseEvent(\n BaseTool tool,\n Map response,\n ToolContext toolContext,\n InvocationContext invocationContext) {\n Tracer tracer = Telemetry.getTracer();\n Span span = tracer.spanBuilder(\"tool_response [\" + tool.name() + \"]\").startSpan();\n try (Scope scope = span.makeCurrent()) {\n // use a empty placeholder response if tool response is null.\n if (response == null) {\n response = new HashMap<>();\n }\n\n Part partFunctionResponse =\n Part.builder()\n .functionResponse(\n FunctionResponse.builder()\n .id(toolContext.functionCallId().orElse(\"\"))\n .name(tool.name())\n .response(response)\n .build())\n .build();\n\n Event event =\n Event.builder()\n .id(Event.generateEventId())\n .invocationId(invocationContext.invocationId())\n .author(invocationContext.agent().name())\n .branch(invocationContext.branch())\n .content(\n Optional.of(\n Content.builder()\n .role(\"user\")\n .parts(Collections.singletonList(partFunctionResponse))\n .build()))\n .actions(toolContext.eventActions())\n .build();\n Telemetry.traceToolResponse(invocationContext, event.id(), event);\n return event;\n } finally {\n span.end();\n }\n }\n\n private Functions() {}\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/llmflows/BaseLlmFlow.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows.llmflows;\n\nimport com.google.adk.Telemetry;\nimport com.google.adk.agents.BaseAgent;\nimport com.google.adk.agents.CallbackContext;\nimport com.google.adk.agents.Callbacks.AfterModelCallback;\nimport com.google.adk.agents.Callbacks.BeforeModelCallback;\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.agents.LiveRequest;\nimport com.google.adk.agents.LlmAgent;\nimport com.google.adk.agents.ReadonlyContext;\nimport com.google.adk.agents.RunConfig.StreamingMode;\nimport com.google.adk.events.Event;\nimport com.google.adk.exceptions.LlmCallsLimitExceededException;\nimport com.google.adk.flows.BaseFlow;\nimport com.google.adk.flows.llmflows.RequestProcessor.RequestProcessingResult;\nimport com.google.adk.flows.llmflows.ResponseProcessor.ResponseProcessingResult;\nimport com.google.adk.models.BaseLlm;\nimport com.google.adk.models.BaseLlmConnection;\nimport com.google.adk.models.LlmRegistry;\nimport com.google.adk.models.LlmRequest;\nimport com.google.adk.models.LlmResponse;\nimport com.google.adk.tools.ToolContext;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Iterables;\nimport com.google.genai.types.FunctionResponse;\nimport io.opentelemetry.api.trace.Span;\nimport io.opentelemetry.api.trace.StatusCode;\nimport io.opentelemetry.context.Scope;\nimport io.reactivex.rxjava3.core.Completable;\nimport io.reactivex.rxjava3.core.Flowable;\nimport io.reactivex.rxjava3.core.Maybe;\nimport io.reactivex.rxjava3.core.Single;\nimport io.reactivex.rxjava3.disposables.Disposable;\nimport io.reactivex.rxjava3.observers.DisposableCompletableObserver;\nimport io.reactivex.rxjava3.schedulers.Schedulers;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.Set;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/** A basic flow that calls the LLM in a loop until a final response is generated. */\npublic abstract class BaseLlmFlow implements BaseFlow {\n private static final Logger logger = LoggerFactory.getLogger(BaseLlmFlow.class);\n\n protected final List requestProcessors;\n protected final List responseProcessors;\n\n // Warning: This is local, in-process state that won't be preserved if the runtime is restarted.\n // \"Max steps\" is experimental and may evolve in the future (e.g., to support persistence).\n protected int stepsCompleted = 0;\n protected final int maxSteps;\n\n public BaseLlmFlow(\n List requestProcessors, List responseProcessors) {\n this(requestProcessors, responseProcessors, /* maxSteps= */ Optional.empty());\n }\n\n public BaseLlmFlow(\n List requestProcessors,\n List responseProcessors,\n Optional maxSteps) {\n this.requestProcessors = requestProcessors;\n this.responseProcessors = responseProcessors;\n this.maxSteps = maxSteps.orElse(Integer.MAX_VALUE);\n }\n\n /**\n * Pre-processes the LLM request before sending it to the LLM. Executes all registered {@link\n * RequestProcessor}.\n */\n protected Single preprocess(\n InvocationContext context, LlmRequest llmRequest) {\n\n List> eventIterables = new ArrayList<>();\n LlmAgent agent = (LlmAgent) context.agent();\n\n Single currentLlmRequest = Single.just(llmRequest);\n for (RequestProcessor processor : requestProcessors) {\n currentLlmRequest =\n currentLlmRequest\n .flatMap(request -> processor.processRequest(context, request))\n .doOnSuccess(\n result -> {\n if (result.events() != null) {\n eventIterables.add(result.events());\n }\n })\n .map(RequestProcessingResult::updatedRequest);\n }\n\n return currentLlmRequest.flatMap(\n processedRequest -> {\n LlmRequest.Builder updatedRequestBuilder = processedRequest.toBuilder();\n\n return agent\n .canonicalTools(new ReadonlyContext(context))\n .concatMapCompletable(\n tool ->\n tool.processLlmRequest(\n updatedRequestBuilder, ToolContext.builder(context).build()))\n .andThen(\n Single.fromCallable(\n () -> {\n Iterable combinedEvents = Iterables.concat(eventIterables);\n return RequestProcessingResult.create(\n updatedRequestBuilder.build(), combinedEvents);\n }));\n });\n }\n\n /**\n * Post-processes the LLM response after receiving it from the LLM. Executes all registered {@link\n * ResponseProcessor} instances. Handles function calls if present in the response.\n */\n protected Single postprocess(\n InvocationContext context,\n Event baseEventForLlmResponse,\n LlmRequest llmRequest,\n LlmResponse llmResponse) {\n\n List> eventIterables = new ArrayList<>();\n Single currentLlmResponse = Single.just(llmResponse);\n for (ResponseProcessor processor : responseProcessors) {\n currentLlmResponse =\n currentLlmResponse\n .flatMap(response -> processor.processResponse(context, response))\n .doOnSuccess(\n result -> {\n if (result.events() != null) {\n eventIterables.add(result.events());\n }\n })\n .map(ResponseProcessingResult::updatedResponse);\n }\n\n return currentLlmResponse.flatMap(\n updatedResponse -> {\n if (updatedResponse.content().isEmpty()\n && updatedResponse.errorCode().isEmpty()\n && !updatedResponse.interrupted().orElse(false)\n && !updatedResponse.turnComplete().orElse(false)) {\n return Single.just(\n ResponseProcessingResult.create(\n updatedResponse, Iterables.concat(eventIterables), Optional.empty()));\n }\n\n Event modelResponseEvent =\n buildModelResponseEvent(baseEventForLlmResponse, llmRequest, updatedResponse);\n eventIterables.add(Collections.singleton(modelResponseEvent));\n\n Maybe maybeFunctionCallEvent =\n modelResponseEvent.functionCalls().isEmpty()\n ? Maybe.empty()\n : Functions.handleFunctionCalls(context, modelResponseEvent, llmRequest.tools());\n\n return maybeFunctionCallEvent\n .map(Optional::of)\n .defaultIfEmpty(Optional.empty())\n .map(\n functionCallEventOpt -> {\n Optional transferToAgent = Optional.empty();\n if (functionCallEventOpt.isPresent()) {\n Event functionCallEvent = functionCallEventOpt.get();\n eventIterables.add(Collections.singleton(functionCallEvent));\n transferToAgent = functionCallEvent.actions().transferToAgent();\n }\n Iterable combinedEvents = Iterables.concat(eventIterables);\n return ResponseProcessingResult.create(\n updatedResponse, combinedEvents, transferToAgent);\n });\n });\n }\n\n /**\n * Sends a request to the LLM and returns its response.\n *\n * @param context The invocation context.\n * @param llmRequest The LLM request.\n * @param eventForCallbackUsage An Event object primarily for providing context (like actions) to\n * callbacks. Callbacks should not rely on its ID if they create their own separate events.\n */\n private Flowable callLlm(\n InvocationContext context, LlmRequest llmRequest, Event eventForCallbackUsage) {\n LlmAgent agent = (LlmAgent) context.agent();\n\n return handleBeforeModelCallback(context, llmRequest, eventForCallbackUsage)\n .flatMapPublisher(\n beforeResponse -> {\n if (beforeResponse.isPresent()) {\n return Flowable.just(beforeResponse.get());\n }\n BaseLlm llm =\n agent.resolvedModel().model().isPresent()\n ? agent.resolvedModel().model().get()\n : LlmRegistry.getLlm(agent.resolvedModel().modelName().get());\n return Flowable.defer(\n () -> {\n Span llmCallSpan =\n Telemetry.getTracer().spanBuilder(\"call_llm\").startSpan();\n\n try (Scope scope = llmCallSpan.makeCurrent()) {\n return llm.generateContent(\n llmRequest,\n context.runConfig().streamingMode() == StreamingMode.SSE)\n .doOnNext(\n llmResp -> {\n try (Scope innerScope = llmCallSpan.makeCurrent()) {\n Telemetry.traceCallLlm(\n context, eventForCallbackUsage.id(), llmRequest, llmResp);\n }\n })\n .doOnError(\n error -> {\n llmCallSpan.setStatus(StatusCode.ERROR, error.getMessage());\n llmCallSpan.recordException(error);\n })\n .doFinally(llmCallSpan::end);\n }\n })\n .concatMap(\n llmResp ->\n handleAfterModelCallback(context, llmResp, eventForCallbackUsage)\n .toFlowable());\n });\n }\n\n /**\n * Invokes {@link BeforeModelCallback}s. If any returns a response, it's used instead of calling\n * the LLM.\n *\n * @return A {@link Single} with the callback result or {@link Optional#empty()}.\n */\n private Single> handleBeforeModelCallback(\n InvocationContext context, LlmRequest llmRequest, Event modelResponseEvent) {\n LlmAgent agent = (LlmAgent) context.agent();\n\n Optional> callbacksOpt = agent.beforeModelCallback();\n if (callbacksOpt.isEmpty() || callbacksOpt.get().isEmpty()) {\n return Single.just(Optional.empty());\n }\n\n Event callbackEvent = modelResponseEvent.toBuilder().build();\n List callbacks = callbacksOpt.get();\n\n return Flowable.fromIterable(callbacks)\n .concatMapSingle(\n callback -> {\n CallbackContext callbackContext =\n new CallbackContext(context, callbackEvent.actions());\n return callback\n .call(callbackContext, llmRequest)\n .map(Optional::of)\n .defaultIfEmpty(Optional.empty());\n })\n .filter(Optional::isPresent)\n .firstElement()\n .switchIfEmpty(Single.just(Optional.empty()));\n }\n\n /**\n * Invokes {@link AfterModelCallback}s after an LLM response. If any returns a response, it\n * replaces the original.\n *\n * @return A {@link Single} with the final {@link LlmResponse}.\n */\n private Single handleAfterModelCallback(\n InvocationContext context, LlmResponse llmResponse, Event modelResponseEvent) {\n LlmAgent agent = (LlmAgent) context.agent();\n Optional> callbacksOpt = agent.afterModelCallback();\n\n if (callbacksOpt.isEmpty() || callbacksOpt.get().isEmpty()) {\n return Single.just(llmResponse);\n }\n\n Event callbackEvent = modelResponseEvent.toBuilder().content(llmResponse.content()).build();\n List callbacks = callbacksOpt.get();\n\n return Flowable.fromIterable(callbacks)\n .concatMapSingle(\n callback -> {\n CallbackContext callbackContext =\n new CallbackContext(context, callbackEvent.actions());\n return callback\n .call(callbackContext, llmResponse)\n .map(Optional::of)\n .defaultIfEmpty(Optional.empty());\n })\n .filter(Optional::isPresent)\n .firstElement()\n .map(Optional::get)\n .switchIfEmpty(Single.just(llmResponse));\n }\n\n /**\n * Executes a single iteration of the LLM flow: preprocessing → LLM call → postprocessing.\n *\n *

Handles early termination, LLM call limits, and agent transfer if needed.\n *\n * @return A {@link Flowable} of {@link Event} objects from this step.\n * @throws LlmCallsLimitExceededException if the agent exceeds allowed LLM invocations.\n * @throws IllegalStateException if a transfer agent is specified but not found.\n */\n private Flowable runOneStep(InvocationContext context) {\n LlmRequest initialLlmRequest = LlmRequest.builder().build();\n\n return preprocess(context, initialLlmRequest)\n .flatMapPublisher(\n preResult -> {\n LlmRequest llmRequestAfterPreprocess = preResult.updatedRequest();\n Iterable preEvents = preResult.events();\n\n if (context.endInvocation()) {\n logger.debug(\"End invocation requested during preprocessing.\");\n return Flowable.fromIterable(preEvents);\n }\n\n try {\n context.incrementLlmCallsCount();\n } catch (LlmCallsLimitExceededException e) {\n logger.error(\"LLM calls limit exceeded.\", e);\n return Flowable.fromIterable(preEvents).concatWith(Flowable.error(e));\n }\n\n final Event mutableEventTemplate =\n Event.builder()\n .id(Event.generateEventId())\n .invocationId(context.invocationId())\n .author(context.agent().name())\n .branch(context.branch())\n .build();\n\n Flowable restOfFlow =\n callLlm(context, llmRequestAfterPreprocess, mutableEventTemplate)\n .concatMap(\n llmResponse -> {\n Single postResultSingle =\n postprocess(\n context,\n mutableEventTemplate,\n llmRequestAfterPreprocess,\n llmResponse);\n\n return postResultSingle\n .doOnSuccess(\n ignored -> {\n String oldId = mutableEventTemplate.id();\n mutableEventTemplate.setId(Event.generateEventId());\n logger.debug(\n \"Updated mutableEventTemplate ID from {} to {} for next\"\n + \" LlmResponse\",\n oldId,\n mutableEventTemplate.id());\n })\n .toFlowable();\n })\n .concatMap(\n postResult -> {\n Flowable postProcessedEvents =\n Flowable.fromIterable(postResult.events());\n if (postResult.transferToAgent().isPresent()) {\n String agentToTransfer = postResult.transferToAgent().get();\n logger.debug(\"Transferring to agent: {}\", agentToTransfer);\n BaseAgent rootAgent = context.agent().rootAgent();\n BaseAgent nextAgent = rootAgent.findAgent(agentToTransfer);\n if (nextAgent == null) {\n String errorMsg =\n \"Agent not found for transfer: \" + agentToTransfer;\n logger.error(errorMsg);\n return postProcessedEvents.concatWith(\n Flowable.error(new IllegalStateException(errorMsg)));\n }\n return postProcessedEvents.concatWith(\n Flowable.defer(() -> nextAgent.runAsync(context)));\n }\n return postProcessedEvents;\n });\n\n return restOfFlow.startWithIterable(preEvents);\n });\n }\n\n /**\n * Executes the full LLM flow by repeatedly calling {@link #runOneStep} until a final response is\n * produced.\n *\n * @return A {@link Flowable} of all {@link Event}s generated during the flow.\n */\n @Override\n public Flowable run(InvocationContext invocationContext) {\n Flowable currentStepEvents = runOneStep(invocationContext).cache();\n if (++stepsCompleted >= maxSteps) {\n logger.debug(\"Ending flow execution because max steps reached.\");\n return currentStepEvents;\n }\n\n return currentStepEvents.concatWith(\n currentStepEvents\n .toList()\n .flatMapPublisher(\n eventList -> {\n if (eventList.isEmpty()\n || Iterables.getLast(eventList).finalResponse()\n || Iterables.getLast(eventList).actions().endInvocation().orElse(false)) {\n logger.debug(\n \"Ending flow execution based on final response, endInvocation action or\"\n + \" empty event list.\");\n return Flowable.empty();\n } else {\n logger.debug(\"Continuing to next step of the flow.\");\n return Flowable.defer(() -> run(invocationContext));\n }\n }));\n }\n\n /**\n * Executes the LLM flow in streaming mode.\n *\n *

Handles sending history and live requests to the LLM, receiving responses, processing them,\n * and managing agent transfers.\n *\n * @return A {@link Flowable} of {@link Event}s streamed in real-time.\n */\n @Override\n public Flowable runLive(InvocationContext invocationContext) {\n LlmRequest llmRequest = LlmRequest.builder().build();\n\n return preprocess(invocationContext, llmRequest)\n .flatMapPublisher(\n preResult -> {\n LlmRequest llmRequestAfterPreprocess = preResult.updatedRequest();\n if (invocationContext.endInvocation()) {\n return Flowable.fromIterable(preResult.events());\n }\n\n String eventIdForSendData = Event.generateEventId();\n LlmAgent agent = (LlmAgent) invocationContext.agent();\n BaseLlm llm =\n agent.resolvedModel().model().isPresent()\n ? agent.resolvedModel().model().get()\n : LlmRegistry.getLlm(agent.resolvedModel().modelName().get());\n BaseLlmConnection connection = llm.connect(llmRequestAfterPreprocess);\n Completable historySent =\n llmRequestAfterPreprocess.contents().isEmpty()\n ? Completable.complete()\n : Completable.defer(\n () -> {\n Span sendDataSpan =\n Telemetry.getTracer().spanBuilder(\"send_data\").startSpan();\n try (Scope scope = sendDataSpan.makeCurrent()) {\n return connection\n .sendHistory(llmRequestAfterPreprocess.contents())\n .doOnComplete(\n () -> {\n try (Scope innerScope = sendDataSpan.makeCurrent()) {\n Telemetry.traceSendData(\n invocationContext,\n eventIdForSendData,\n llmRequestAfterPreprocess.contents());\n }\n })\n .doOnError(\n error -> {\n sendDataSpan.setStatus(\n StatusCode.ERROR, error.getMessage());\n sendDataSpan.recordException(error);\n try (Scope innerScope = sendDataSpan.makeCurrent()) {\n Telemetry.traceSendData(\n invocationContext,\n eventIdForSendData,\n llmRequestAfterPreprocess.contents());\n }\n })\n .doFinally(sendDataSpan::end);\n }\n });\n\n Flowable liveRequests = invocationContext.liveRequestQueue().get().get();\n Disposable sendTask =\n historySent\n .observeOn(agent.executor().map(Schedulers::from).orElse(Schedulers.io()))\n .andThen(\n liveRequests\n .onBackpressureBuffer()\n .concatMapCompletable(\n request -> {\n if (request.content().isPresent()) {\n return connection.sendContent(request.content().get());\n } else if (request.blob().isPresent()) {\n return connection.sendRealtime(request.blob().get());\n }\n return Completable.fromAction(connection::close);\n }))\n .subscribeWith(\n new DisposableCompletableObserver() {\n @Override\n public void onComplete() {\n connection.close();\n }\n\n @Override\n public void onError(Throwable e) {\n connection.close(e);\n }\n });\n\n Event.Builder liveEventBuilderTemplate =\n Event.builder()\n .invocationId(invocationContext.invocationId())\n .author(invocationContext.agent().name())\n .branch(invocationContext.branch());\n\n Flowable receiveFlow =\n connection\n .receive()\n .flatMapSingle(\n llmResponse -> {\n Event baseEventForThisLlmResponse =\n liveEventBuilderTemplate.id(Event.generateEventId()).build();\n return postprocess(\n invocationContext,\n baseEventForThisLlmResponse,\n llmRequestAfterPreprocess,\n llmResponse);\n })\n .flatMap(\n postResult -> {\n Flowable events = Flowable.fromIterable(postResult.events());\n if (postResult.transferToAgent().isPresent()) {\n BaseAgent rootAgent = invocationContext.agent().rootAgent();\n BaseAgent nextAgent =\n rootAgent.findAgent(postResult.transferToAgent().get());\n if (nextAgent == null) {\n throw new IllegalStateException(\n \"Agent not found: \" + postResult.transferToAgent().get());\n }\n Flowable nextAgentEvents =\n nextAgent.runLive(invocationContext);\n events = Flowable.concat(events, nextAgentEvents);\n }\n return events;\n })\n .doOnNext(\n event -> {\n ImmutableList functionResponses =\n event.functionResponses();\n if (!functionResponses.isEmpty()) {\n invocationContext\n .liveRequestQueue()\n .get()\n .content(event.content().get());\n }\n if (functionResponses.stream()\n .anyMatch(\n functionResponse ->\n functionResponse\n .name()\n .orElse(\"\")\n .equals(\"transferToAgent\"))\n || event.actions().endInvocation().orElse(false)) {\n sendTask.dispose();\n connection.close();\n }\n });\n\n return receiveFlow\n .takeWhile(event -> !event.actions().endInvocation().orElse(false))\n .startWithIterable(preResult.events());\n });\n }\n\n /**\n * Builds an {@link Event} from LLM response, request, and base event data.\n *\n *

Populates the event with LLM output and tool function call metadata.\n *\n * @return A fully constructed {@link Event} representing the LLM response.\n */\n private Event buildModelResponseEvent(\n Event baseEventForLlmResponse, LlmRequest llmRequest, LlmResponse llmResponse) {\n Event.Builder eventBuilder =\n baseEventForLlmResponse.toBuilder()\n .content(llmResponse.content())\n .partial(llmResponse.partial())\n .errorCode(llmResponse.errorCode())\n .errorMessage(llmResponse.errorMessage())\n .interrupted(llmResponse.interrupted())\n .turnComplete(llmResponse.turnComplete())\n .groundingMetadata(llmResponse.groundingMetadata());\n\n Event event = eventBuilder.build();\n\n if (!event.functionCalls().isEmpty()) {\n Functions.populateClientFunctionCallId(event);\n Set longRunningToolIds =\n Functions.getLongRunningFunctionCalls(event.functionCalls(), llmRequest.tools());\n if (!longRunningToolIds.isEmpty()) {\n event.setLongRunningToolIds(Optional.of(longRunningToolIds));\n }\n }\n return event;\n }\n}\n"], ["/adk-java/contrib/langchain4j/src/main/java/com/google/adk/models/langchain4j/LangChain4j.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.google.adk.models.langchain4j;\n\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.google.adk.models.BaseLlm;\nimport com.google.adk.models.BaseLlmConnection;\nimport com.google.adk.models.LlmRequest;\nimport com.google.adk.models.LlmResponse;\nimport com.google.genai.types.Blob;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.FunctionCall;\nimport com.google.genai.types.FunctionCallingConfigMode;\nimport com.google.genai.types.FunctionDeclaration;\nimport com.google.genai.types.FunctionResponse;\nimport com.google.genai.types.GenerateContentConfig;\nimport com.google.genai.types.Part;\nimport com.google.genai.types.Schema;\nimport com.google.genai.types.ToolConfig;\nimport com.google.genai.types.Type;\nimport dev.langchain4j.Experimental;\nimport dev.langchain4j.agent.tool.ToolExecutionRequest;\nimport dev.langchain4j.agent.tool.ToolSpecification;\nimport dev.langchain4j.data.audio.Audio;\nimport dev.langchain4j.data.image.Image;\nimport dev.langchain4j.data.message.AiMessage;\nimport dev.langchain4j.data.message.AudioContent;\nimport dev.langchain4j.data.message.ChatMessage;\nimport dev.langchain4j.data.message.ImageContent;\nimport dev.langchain4j.data.message.PdfFileContent;\nimport dev.langchain4j.data.message.SystemMessage;\nimport dev.langchain4j.data.message.TextContent;\nimport dev.langchain4j.data.message.ToolExecutionResultMessage;\nimport dev.langchain4j.data.message.UserMessage;\nimport dev.langchain4j.data.message.VideoContent;\nimport dev.langchain4j.data.pdf.PdfFile;\nimport dev.langchain4j.data.video.Video;\nimport dev.langchain4j.exception.UnsupportedFeatureException;\nimport dev.langchain4j.model.chat.ChatModel;\nimport dev.langchain4j.model.chat.StreamingChatModel;\nimport dev.langchain4j.model.chat.request.ChatRequest;\nimport dev.langchain4j.model.chat.request.ToolChoice;\nimport dev.langchain4j.model.chat.request.json.JsonArraySchema;\nimport dev.langchain4j.model.chat.request.json.JsonBooleanSchema;\nimport dev.langchain4j.model.chat.request.json.JsonIntegerSchema;\nimport dev.langchain4j.model.chat.request.json.JsonNumberSchema;\nimport dev.langchain4j.model.chat.request.json.JsonObjectSchema;\nimport dev.langchain4j.model.chat.request.json.JsonSchemaElement;\nimport dev.langchain4j.model.chat.request.json.JsonStringSchema;\nimport dev.langchain4j.model.chat.response.ChatResponse;\nimport dev.langchain4j.model.chat.response.StreamingChatResponseHandler;\nimport io.reactivex.rxjava3.core.BackpressureStrategy;\nimport io.reactivex.rxjava3.core.Flowable;\nimport java.util.ArrayList;\nimport java.util.Base64;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.UUID;\n\n@Experimental\npublic class LangChain4j extends BaseLlm {\n\n private static final TypeReference> MAP_TYPE_REFERENCE =\n new TypeReference<>() {};\n\n private final ChatModel chatModel;\n private final StreamingChatModel streamingChatModel;\n private final ObjectMapper objectMapper;\n\n public LangChain4j(ChatModel chatModel) {\n super(\n Objects.requireNonNull(\n chatModel.defaultRequestParameters().modelName(), \"chat model name cannot be null\"));\n this.chatModel = Objects.requireNonNull(chatModel, \"chatModel cannot be null\");\n this.streamingChatModel = null;\n this.objectMapper = new ObjectMapper();\n }\n\n public LangChain4j(ChatModel chatModel, String modelName) {\n super(Objects.requireNonNull(modelName, \"chat model name cannot be null\"));\n this.chatModel = Objects.requireNonNull(chatModel, \"chatModel cannot be null\");\n this.streamingChatModel = null;\n this.objectMapper = new ObjectMapper();\n }\n\n public LangChain4j(StreamingChatModel streamingChatModel) {\n super(\n Objects.requireNonNull(\n streamingChatModel.defaultRequestParameters().modelName(),\n \"streaming chat model name cannot be null\"));\n this.chatModel = null;\n this.streamingChatModel =\n Objects.requireNonNull(streamingChatModel, \"streamingChatModel cannot be null\");\n this.objectMapper = new ObjectMapper();\n }\n\n public LangChain4j(StreamingChatModel streamingChatModel, String modelName) {\n super(Objects.requireNonNull(modelName, \"streaming chat model name cannot be null\"));\n this.chatModel = null;\n this.streamingChatModel =\n Objects.requireNonNull(streamingChatModel, \"streamingChatModel cannot be null\");\n this.objectMapper = new ObjectMapper();\n }\n\n public LangChain4j(ChatModel chatModel, StreamingChatModel streamingChatModel, String modelName) {\n super(Objects.requireNonNull(modelName, \"model name cannot be null\"));\n this.chatModel = Objects.requireNonNull(chatModel, \"chatModel cannot be null\");\n this.streamingChatModel =\n Objects.requireNonNull(streamingChatModel, \"streamingChatModel cannot be null\");\n this.objectMapper = new ObjectMapper();\n }\n\n @Override\n public Flowable generateContent(LlmRequest llmRequest, boolean stream) {\n if (stream) {\n if (this.streamingChatModel == null) {\n return Flowable.error(new IllegalStateException(\"StreamingChatModel is not configured\"));\n }\n\n ChatRequest chatRequest = toChatRequest(llmRequest);\n\n return Flowable.create(\n emitter -> {\n streamingChatModel.chat(\n chatRequest,\n new StreamingChatResponseHandler() {\n @Override\n public void onPartialResponse(String s) {\n emitter.onNext(\n LlmResponse.builder().content(Content.fromParts(Part.fromText(s))).build());\n }\n\n @Override\n public void onCompleteResponse(ChatResponse chatResponse) {\n if (chatResponse.aiMessage().hasToolExecutionRequests()) {\n AiMessage aiMessage = chatResponse.aiMessage();\n toParts(aiMessage).stream()\n .map(Part::functionCall)\n .forEach(\n functionCall -> {\n functionCall.ifPresent(\n function -> {\n emitter.onNext(\n LlmResponse.builder()\n .content(\n Content.fromParts(\n Part.fromFunctionCall(\n function.name().orElse(\"\"),\n function.args().orElse(Map.of()))))\n .build());\n });\n });\n }\n emitter.onComplete();\n }\n\n @Override\n public void onError(Throwable throwable) {\n emitter.onError(throwable);\n }\n });\n },\n BackpressureStrategy.BUFFER);\n } else {\n if (this.chatModel == null) {\n return Flowable.error(new IllegalStateException(\"ChatModel is not configured\"));\n }\n\n ChatRequest chatRequest = toChatRequest(llmRequest);\n ChatResponse chatResponse = chatModel.chat(chatRequest);\n LlmResponse llmResponse = toLlmResponse(chatResponse);\n\n return Flowable.just(llmResponse);\n }\n }\n\n private ChatRequest toChatRequest(LlmRequest llmRequest) {\n ChatRequest.Builder requestBuilder = ChatRequest.builder();\n\n List toolSpecifications = toToolSpecifications(llmRequest);\n requestBuilder.toolSpecifications(toolSpecifications);\n\n if (llmRequest.config().isPresent()) {\n GenerateContentConfig generateContentConfig = llmRequest.config().get();\n\n generateContentConfig\n .temperature()\n .ifPresent(temp -> requestBuilder.temperature(temp.doubleValue()));\n generateContentConfig.topP().ifPresent(topP -> requestBuilder.topP(topP.doubleValue()));\n generateContentConfig.topK().ifPresent(topK -> requestBuilder.topK(topK.intValue()));\n generateContentConfig.maxOutputTokens().ifPresent(requestBuilder::maxOutputTokens);\n generateContentConfig.stopSequences().ifPresent(requestBuilder::stopSequences);\n generateContentConfig\n .frequencyPenalty()\n .ifPresent(freqPenalty -> requestBuilder.frequencyPenalty(freqPenalty.doubleValue()));\n generateContentConfig\n .presencePenalty()\n .ifPresent(presPenalty -> requestBuilder.presencePenalty(presPenalty.doubleValue()));\n\n if (generateContentConfig.toolConfig().isPresent()) {\n ToolConfig toolConfig = generateContentConfig.toolConfig().get();\n toolConfig\n .functionCallingConfig()\n .ifPresent(\n functionCallingConfig -> {\n functionCallingConfig\n .mode()\n .ifPresent(\n functionMode -> {\n if (functionMode\n .knownEnum()\n .equals(FunctionCallingConfigMode.Known.AUTO)) {\n requestBuilder.toolChoice(ToolChoice.AUTO);\n } else if (functionMode\n .knownEnum()\n .equals(FunctionCallingConfigMode.Known.ANY)) {\n // TODO check if it's the correct\n // mapping\n requestBuilder.toolChoice(ToolChoice.REQUIRED);\n functionCallingConfig\n .allowedFunctionNames()\n .ifPresent(\n allowedFunctionNames -> {\n requestBuilder.toolSpecifications(\n toolSpecifications.stream()\n .filter(\n toolSpecification ->\n allowedFunctionNames.contains(\n toolSpecification.name()))\n .toList());\n });\n } else if (functionMode\n .knownEnum()\n .equals(FunctionCallingConfigMode.Known.NONE)) {\n requestBuilder.toolSpecifications(List.of());\n }\n });\n });\n toolConfig\n .retrievalConfig()\n .ifPresent(\n retrievalConfig -> {\n // TODO? It exposes Latitude / Longitude, what to do with this?\n });\n }\n }\n\n return requestBuilder.messages(toMessages(llmRequest)).build();\n }\n\n private List toMessages(LlmRequest llmRequest) {\n List messages =\n new ArrayList<>(\n llmRequest.getSystemInstructions().stream().map(SystemMessage::from).toList());\n llmRequest.contents().forEach(content -> messages.addAll(toChatMessage(content)));\n return messages;\n }\n\n private List toChatMessage(Content content) {\n String role = content.role().orElseThrow().toLowerCase();\n return switch (role) {\n case \"user\" -> toUserOrToolResultMessage(content);\n case \"model\", \"assistant\" -> List.of(toAiMessage(content));\n default -> throw new IllegalStateException(\"Unexpected role: \" + role);\n };\n }\n\n private List toUserOrToolResultMessage(Content content) {\n List toolExecutionResultMessages = new ArrayList<>();\n List toolExecutionRequests = new ArrayList<>();\n\n List lc4jContents = new ArrayList<>();\n\n for (Part part : content.parts().orElse(List.of())) {\n if (part.text().isPresent()) {\n lc4jContents.add(TextContent.from(part.text().get()));\n } else if (part.functionResponse().isPresent()) {\n FunctionResponse functionResponse = part.functionResponse().get();\n toolExecutionResultMessages.add(\n ToolExecutionResultMessage.from(\n functionResponse.id().orElseThrow(),\n functionResponse.name().orElseThrow(),\n toJson(functionResponse.response().orElseThrow())));\n } else if (part.functionCall().isPresent()) {\n FunctionCall functionCall = part.functionCall().get();\n toolExecutionRequests.add(\n ToolExecutionRequest.builder()\n .id(functionCall.id().orElseThrow())\n .name(functionCall.name().orElseThrow())\n .arguments(toJson(functionCall.args().orElse(Map.of())))\n .build());\n } else if (part.inlineData().isPresent()) {\n Blob blob = part.inlineData().get();\n\n if (blob.mimeType().isEmpty() || blob.data().isEmpty()) {\n throw new IllegalArgumentException(\"Mime type and data required\");\n }\n\n byte[] bytes = blob.data().get();\n String mimeType = blob.mimeType().get();\n\n Base64.Encoder encoder = Base64.getEncoder();\n\n dev.langchain4j.data.message.Content lc4jContent = null;\n\n if (mimeType.startsWith(\"audio/\")) {\n lc4jContent =\n AudioContent.from(\n Audio.builder()\n .base64Data(encoder.encodeToString(bytes))\n .mimeType(mimeType)\n .build());\n } else if (mimeType.startsWith(\"video/\")) {\n lc4jContent =\n VideoContent.from(\n Video.builder()\n .base64Data(encoder.encodeToString(bytes))\n .mimeType(mimeType)\n .build());\n } else if (mimeType.startsWith(\"image/\")) {\n lc4jContent =\n ImageContent.from(\n Image.builder()\n .base64Data(encoder.encodeToString(bytes))\n .mimeType(mimeType)\n .build());\n } else if (mimeType.startsWith(\"application/pdf\")) {\n lc4jContent =\n PdfFileContent.from(\n PdfFile.builder()\n .base64Data(encoder.encodeToString(bytes))\n .mimeType(mimeType)\n .build());\n } else if (mimeType.startsWith(\"text/\")\n || mimeType.equals(\"application/json\")\n || mimeType.endsWith(\"+json\")\n || mimeType.endsWith(\"+xml\")) {\n // TODO are there missing text based mime types?\n // TODO should we assume UTF_8?\n lc4jContents.add(\n TextContent.from(new String(bytes, java.nio.charset.StandardCharsets.UTF_8)));\n }\n\n if (lc4jContent != null) {\n lc4jContents.add(lc4jContent);\n } else {\n throw new IllegalArgumentException(\"Unknown or unhandled mime type: \" + mimeType);\n }\n } else {\n throw new IllegalStateException(\n \"Text, media or functionCall is expected, but was: \" + part);\n }\n }\n\n if (!toolExecutionResultMessages.isEmpty()) {\n return new ArrayList(toolExecutionResultMessages);\n } else if (!toolExecutionRequests.isEmpty()) {\n return toolExecutionRequests.stream()\n .map(AiMessage::aiMessage)\n .map(msg -> (ChatMessage) msg)\n .toList();\n } else {\n return List.of(UserMessage.from(lc4jContents));\n }\n }\n\n private AiMessage toAiMessage(Content content) {\n List texts = new ArrayList<>();\n List toolExecutionRequests = new ArrayList<>();\n\n content\n .parts()\n .orElse(List.of())\n .forEach(\n part -> {\n if (part.text().isPresent()) {\n texts.add(part.text().get());\n } else if (part.functionCall().isPresent()) {\n FunctionCall functionCall = part.functionCall().get();\n ToolExecutionRequest toolExecutionRequest =\n ToolExecutionRequest.builder()\n .id(functionCall.id().orElseThrow())\n .name(functionCall.name().orElseThrow())\n .arguments(toJson(functionCall.args().orElseThrow()))\n .build();\n toolExecutionRequests.add(toolExecutionRequest);\n } else {\n throw new IllegalStateException(\n \"Either text or functionCall is expected, but was: \" + part);\n }\n });\n\n return AiMessage.builder()\n .text(String.join(\"\\n\", texts))\n .toolExecutionRequests(toolExecutionRequests)\n .build();\n }\n\n private String toJson(Object object) {\n try {\n return objectMapper.writeValueAsString(object);\n } catch (JsonProcessingException e) {\n throw new RuntimeException(e);\n }\n }\n\n private List toToolSpecifications(LlmRequest llmRequest) {\n List toolSpecifications = new ArrayList<>();\n\n llmRequest\n .tools()\n .values()\n .forEach(\n baseTool -> {\n if (baseTool.declaration().isPresent()) {\n FunctionDeclaration functionDeclaration = baseTool.declaration().get();\n if (functionDeclaration.parameters().isPresent()) {\n Schema schema = functionDeclaration.parameters().get();\n ToolSpecification toolSpecification =\n ToolSpecification.builder()\n .name(baseTool.name())\n .description(baseTool.description())\n .parameters(toParameters(schema))\n .build();\n toolSpecifications.add(toolSpecification);\n } else {\n // TODO exception or something else?\n throw new IllegalStateException(\"Tool lacking parameters: \" + baseTool);\n }\n } else {\n // TODO exception or something else?\n throw new IllegalStateException(\"Tool lacking declaration: \" + baseTool);\n }\n });\n\n return toolSpecifications;\n }\n\n private JsonObjectSchema toParameters(Schema schema) {\n if (schema.type().isPresent() && schema.type().get().knownEnum().equals(Type.Known.OBJECT)) {\n return JsonObjectSchema.builder()\n .addProperties(toProperties(schema))\n .required(schema.required().orElse(List.of()))\n .build();\n } else {\n throw new UnsupportedOperationException(\n \"LangChain4jLlm does not support schema of type: \" + schema.type());\n }\n }\n\n private Map toProperties(Schema schema) {\n Map properties = schema.properties().orElse(Map.of());\n Map result = new HashMap<>();\n properties.forEach((k, v) -> result.put(k, toJsonSchemaElement(v)));\n return result;\n }\n\n private JsonSchemaElement toJsonSchemaElement(Schema schema) {\n if (schema != null && schema.type().isPresent()) {\n Type type = schema.type().get();\n return switch (type.knownEnum()) {\n case STRING ->\n JsonStringSchema.builder().description(schema.description().orElse(null)).build();\n case NUMBER ->\n JsonNumberSchema.builder().description(schema.description().orElse(null)).build();\n case INTEGER ->\n JsonIntegerSchema.builder().description(schema.description().orElse(null)).build();\n case BOOLEAN ->\n JsonBooleanSchema.builder().description(schema.description().orElse(null)).build();\n case ARRAY ->\n JsonArraySchema.builder()\n .description(schema.description().orElse(null))\n .items(toJsonSchemaElement(schema.items().orElseThrow()))\n .build();\n case OBJECT -> toParameters(schema);\n case TYPE_UNSPECIFIED ->\n throw new UnsupportedFeatureException(\n \"LangChain4jLlm does not support schema of type: \" + type);\n };\n } else {\n throw new IllegalArgumentException(\"Schema type cannot be null or absent\");\n }\n }\n\n private LlmResponse toLlmResponse(ChatResponse chatResponse) {\n Content content =\n Content.builder().role(\"model\").parts(toParts(chatResponse.aiMessage())).build();\n\n return LlmResponse.builder().content(content).build();\n }\n\n private List toParts(AiMessage aiMessage) {\n if (aiMessage.hasToolExecutionRequests()) {\n List parts = new ArrayList<>();\n aiMessage\n .toolExecutionRequests()\n .forEach(\n toolExecutionRequest -> {\n FunctionCall functionCall =\n FunctionCall.builder()\n .id(\n toolExecutionRequest.id() != null\n ? toolExecutionRequest.id()\n : UUID.randomUUID().toString())\n .name(toolExecutionRequest.name())\n .args(toArgs(toolExecutionRequest))\n .build();\n Part part = Part.builder().functionCall(functionCall).build();\n parts.add(part);\n });\n return parts;\n } else {\n Part part = Part.builder().text(aiMessage.text()).build();\n return List.of(part);\n }\n }\n\n private Map toArgs(ToolExecutionRequest toolExecutionRequest) {\n try {\n return objectMapper.readValue(toolExecutionRequest.arguments(), MAP_TYPE_REFERENCE);\n } catch (JsonProcessingException e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public BaseLlmConnection connect(LlmRequest llmRequest) {\n throw new UnsupportedOperationException(\n \"Live connection is not supported for LangChain4j models.\");\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/agents/BaseAgent.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.agents;\n\nimport static com.google.common.collect.ImmutableList.toImmutableList;\n\nimport com.google.adk.Telemetry;\nimport com.google.adk.agents.Callbacks.AfterAgentCallback;\nimport com.google.adk.agents.Callbacks.BeforeAgentCallback;\nimport com.google.adk.events.Event;\nimport com.google.common.collect.ImmutableList;\nimport com.google.genai.types.Content;\nimport io.opentelemetry.api.trace.Span;\nimport io.opentelemetry.api.trace.Tracer;\nimport io.opentelemetry.context.Scope;\nimport io.reactivex.rxjava3.core.Flowable;\nimport io.reactivex.rxjava3.core.Maybe;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.function.Function;\nimport org.jspecify.annotations.Nullable;\n\n/** Base class for all agents. */\npublic abstract class BaseAgent {\n\n /** The agent's name. Must be a unique identifier within the agent tree. */\n private final String name;\n\n /**\n * One line description about the agent's capability. The system can use this for decision-making\n * when delegating control to different agents.\n */\n private final String description;\n\n /**\n * The parent agent in the agent tree. Note that one agent cannot be added to two different\n * parents' sub-agents lists.\n */\n private BaseAgent parentAgent;\n\n private final List subAgents;\n\n private final Optional> beforeAgentCallback;\n private final Optional> afterAgentCallback;\n\n /**\n * Creates a new BaseAgent.\n *\n * @param name Unique agent name. Cannot be \"user\" (reserved).\n * @param description Agent purpose.\n * @param subAgents Agents managed by this agent.\n * @param beforeAgentCallback Callbacks before agent execution. Invoked in order until one doesn't\n * return null.\n * @param afterAgentCallback Callbacks after agent execution. Invoked in order until one doesn't\n * return null.\n */\n public BaseAgent(\n String name,\n String description,\n List subAgents,\n List beforeAgentCallback,\n List afterAgentCallback) {\n this.name = name;\n this.description = description;\n this.parentAgent = null;\n this.subAgents = subAgents != null ? subAgents : ImmutableList.of();\n this.beforeAgentCallback = Optional.ofNullable(beforeAgentCallback);\n this.afterAgentCallback = Optional.ofNullable(afterAgentCallback);\n\n // Establish parent relationships for all sub-agents if needed.\n for (BaseAgent subAgent : this.subAgents) {\n subAgent.parentAgent(this);\n }\n }\n\n /**\n * Gets the agent's unique name.\n *\n * @return the unique name of the agent.\n */\n public final String name() {\n return name;\n }\n\n /**\n * Gets the one-line description of the agent's capability.\n *\n * @return the description of the agent.\n */\n public final String description() {\n return description;\n }\n\n /**\n * Retrieves the parent agent in the agent tree.\n *\n * @return the parent agent, or {@code null} if this agent does not have a parent.\n */\n public BaseAgent parentAgent() {\n return parentAgent;\n }\n\n /**\n * Sets the parent agent.\n *\n * @param parentAgent The parent agent to set.\n */\n protected void parentAgent(BaseAgent parentAgent) {\n this.parentAgent = parentAgent;\n }\n\n /**\n * Returns the root agent for this agent by traversing up the parent chain.\n *\n * @return the root agent.\n */\n public BaseAgent rootAgent() {\n BaseAgent agent = this;\n while (agent.parentAgent() != null) {\n agent = agent.parentAgent();\n }\n return agent;\n }\n\n /**\n * Finds an agent (this or descendant) by name.\n *\n * @return the agent or descendant with the given name, or {@code null} if not found.\n */\n public BaseAgent findAgent(String name) {\n if (this.name().equals(name)) {\n return this;\n }\n return findSubAgent(name);\n }\n\n /** Recursively search sub agent by name. */\n public @Nullable BaseAgent findSubAgent(String name) {\n for (BaseAgent subAgent : subAgents) {\n if (subAgent.name().equals(name)) {\n return subAgent;\n }\n BaseAgent result = subAgent.findSubAgent(name);\n if (result != null) {\n return result;\n }\n }\n return null;\n }\n\n public List subAgents() {\n return subAgents;\n }\n\n public Optional> beforeAgentCallback() {\n return beforeAgentCallback;\n }\n\n public Optional> afterAgentCallback() {\n return afterAgentCallback;\n }\n\n /**\n * Creates a shallow copy of the parent context with the agent properly being set to this\n * instance.\n *\n * @param parentContext Parent context to copy.\n * @return new context with updated branch name.\n */\n private InvocationContext createInvocationContext(InvocationContext parentContext) {\n InvocationContext invocationContext = InvocationContext.copyOf(parentContext);\n invocationContext.agent(this);\n // Check for branch to be truthy (not None, not empty string),\n if (parentContext.branch().filter(s -> !s.isEmpty()).isPresent()) {\n invocationContext.branch(parentContext.branch().get() + \".\" + name());\n }\n return invocationContext;\n }\n\n /**\n * Runs the agent asynchronously.\n *\n * @param parentContext Parent context to inherit.\n * @return stream of agent-generated events.\n */\n public Flowable runAsync(InvocationContext parentContext) {\n Tracer tracer = Telemetry.getTracer();\n return Flowable.defer(\n () -> {\n Span span = tracer.spanBuilder(\"agent_run [\" + name() + \"]\").startSpan();\n try (Scope scope = span.makeCurrent()) {\n InvocationContext invocationContext = createInvocationContext(parentContext);\n\n Flowable executionFlowable =\n beforeAgentCallback\n .map(\n callback ->\n callCallback(beforeCallbacksToFunctions(callback), invocationContext))\n .orElse(Single.just(Optional.empty()))\n .flatMapPublisher(\n beforeEventOpt -> {\n if (invocationContext.endInvocation()) {\n return Flowable.fromOptional(beforeEventOpt);\n }\n\n Flowable beforeEvents = Flowable.fromOptional(beforeEventOpt);\n Flowable mainEvents =\n Flowable.defer(() -> runAsyncImpl(invocationContext));\n Flowable afterEvents =\n afterAgentCallback\n .map(\n callback ->\n Flowable.defer(\n () ->\n callCallback(\n afterCallbacksToFunctions(callback),\n invocationContext)\n .flatMapPublisher(Flowable::fromOptional)))\n .orElse(Flowable.empty());\n\n return Flowable.concat(beforeEvents, mainEvents, afterEvents);\n });\n return executionFlowable.doFinally(span::end);\n }\n });\n }\n\n /**\n * Converts before-agent callbacks to functions.\n *\n * @param callbacks Before-agent callbacks.\n * @return callback functions.\n */\n private ImmutableList>> beforeCallbacksToFunctions(\n List callbacks) {\n return callbacks.stream()\n .map(callback -> (Function>) callback::call)\n .collect(toImmutableList());\n }\n\n /**\n * Converts after-agent callbacks to functions.\n *\n * @param callbacks After-agent callbacks.\n * @return callback functions.\n */\n private ImmutableList>> afterCallbacksToFunctions(\n List callbacks) {\n return callbacks.stream()\n .map(callback -> (Function>) callback::call)\n .collect(toImmutableList());\n }\n\n /**\n * Calls agent callbacks and returns the first produced event, if any.\n *\n * @param agentCallbacks Callback functions.\n * @param invocationContext Current invocation context.\n * @return single emitting first event, or empty if none.\n */\n private Single> callCallback(\n List>> agentCallbacks,\n InvocationContext invocationContext) {\n if (agentCallbacks == null || agentCallbacks.isEmpty()) {\n return Single.just(Optional.empty());\n }\n\n CallbackContext callbackContext =\n new CallbackContext(invocationContext, /* eventActions= */ null);\n\n return Flowable.fromIterable(agentCallbacks)\n .concatMap(\n callback -> {\n Maybe maybeContent = callback.apply(callbackContext);\n\n return maybeContent\n .map(\n content -> {\n Event.Builder eventBuilder =\n Event.builder()\n .id(Event.generateEventId())\n .invocationId(invocationContext.invocationId())\n .author(name())\n .branch(invocationContext.branch())\n .actions(callbackContext.eventActions());\n\n eventBuilder.content(Optional.of(content));\n invocationContext.setEndInvocation(true);\n return Optional.of(eventBuilder.build());\n })\n .toFlowable();\n })\n .firstElement()\n .switchIfEmpty(\n Single.defer(\n () -> {\n if (callbackContext.state().hasDelta()) {\n Event.Builder eventBuilder =\n Event.builder()\n .id(Event.generateEventId())\n .invocationId(invocationContext.invocationId())\n .author(name())\n .branch(invocationContext.branch())\n .actions(callbackContext.eventActions());\n\n return Single.just(Optional.of(eventBuilder.build()));\n } else {\n return Single.just(Optional.empty());\n }\n }));\n }\n\n /**\n * Runs the agent synchronously.\n *\n * @param parentContext Parent context to inherit.\n * @return stream of agent-generated events.\n */\n public Flowable runLive(InvocationContext parentContext) {\n Tracer tracer = Telemetry.getTracer();\n return Flowable.defer(\n () -> {\n Span span = tracer.spanBuilder(\"agent_run [\" + name() + \"]\").startSpan();\n try (Scope scope = span.makeCurrent()) {\n InvocationContext invocationContext = createInvocationContext(parentContext);\n Flowable executionFlowable = runLiveImpl(invocationContext);\n return executionFlowable.doFinally(span::end);\n }\n });\n }\n\n /**\n * Agent-specific asynchronous logic.\n *\n * @param invocationContext Current invocation context.\n * @return stream of agent-generated events.\n */\n protected abstract Flowable runAsyncImpl(InvocationContext invocationContext);\n\n /**\n * Agent-specific synchronous logic.\n *\n * @param invocationContext Current invocation context.\n * @return stream of agent-generated events.\n */\n protected abstract Flowable runLiveImpl(InvocationContext invocationContext);\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/AgentTool.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools;\n\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.google.adk.JsonBaseModel;\nimport com.google.adk.SchemaUtils;\nimport com.google.adk.agents.BaseAgent;\nimport com.google.adk.agents.LlmAgent;\nimport com.google.adk.events.Event;\nimport com.google.adk.runner.InMemoryRunner;\nimport com.google.adk.runner.Runner;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.FunctionDeclaration;\nimport com.google.genai.types.Part;\nimport com.google.genai.types.Schema;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.Map;\nimport java.util.Optional;\n\n/** AgentTool implements a tool that allows an agent to call another agent. */\npublic class AgentTool extends BaseTool {\n\n private final BaseAgent agent;\n private final boolean skipSummarization;\n\n public static AgentTool create(BaseAgent agent, boolean skipSummarization) {\n return new AgentTool(agent, skipSummarization);\n }\n\n public static AgentTool create(BaseAgent agent) {\n return new AgentTool(agent, false);\n }\n\n protected AgentTool(BaseAgent agent, boolean skipSummarization) {\n super(agent.name(), agent.description());\n this.agent = agent;\n this.skipSummarization = skipSummarization;\n }\n\n @Override\n public Optional declaration() {\n FunctionDeclaration.Builder builder =\n FunctionDeclaration.builder().description(this.description()).name(this.name());\n\n Optional agentInputSchema = Optional.empty();\n if (agent instanceof LlmAgent llmAgent) {\n agentInputSchema = llmAgent.inputSchema();\n }\n\n if (agentInputSchema.isPresent()) {\n builder.parameters(agentInputSchema.get());\n } else {\n builder.parameters(\n Schema.builder()\n .type(\"OBJECT\")\n .properties(ImmutableMap.of(\"request\", Schema.builder().type(\"STRING\").build()))\n .required(ImmutableList.of(\"request\"))\n .build());\n }\n return Optional.of(builder.build());\n }\n\n @Override\n public Single> runAsync(Map args, ToolContext toolContext) {\n\n if (this.skipSummarization) {\n toolContext.actions().setSkipSummarization(true);\n }\n\n Optional agentInputSchema = Optional.empty();\n if (agent instanceof LlmAgent llmAgent) {\n agentInputSchema = llmAgent.inputSchema();\n }\n\n final Content content;\n if (agentInputSchema.isPresent()) {\n SchemaUtils.validateMapOnSchema(args, agentInputSchema.get(), true);\n try {\n content =\n Content.fromParts(Part.fromText(JsonBaseModel.getMapper().writeValueAsString(args)));\n } catch (JsonProcessingException e) {\n return Single.error(\n new RuntimeException(\"Error serializing tool arguments to JSON: \" + args, e));\n }\n } else {\n Object input = args.get(\"request\");\n content = Content.fromParts(Part.fromText(input.toString()));\n }\n\n Runner runner = new InMemoryRunner(this.agent, toolContext.agentName());\n // Session state is final, can't update to toolContext state\n // session.toBuilder().setState(toolContext.getState());\n return runner\n .sessionService()\n .createSession(toolContext.agentName(), \"tmp-user\", toolContext.state(), null)\n .flatMapPublisher(session -> runner.runAsync(session.userId(), session.id(), content))\n .lastElement()\n .map(Optional::of)\n .defaultIfEmpty(Optional.empty())\n .map(\n optionalLastEvent -> {\n if (optionalLastEvent.isEmpty()) {\n return ImmutableMap.of();\n }\n Event lastEvent = optionalLastEvent.get();\n Optional outputText =\n lastEvent\n .content()\n .flatMap(Content::parts)\n .filter(parts -> !parts.isEmpty())\n .flatMap(parts -> parts.get(0).text());\n\n if (outputText.isEmpty()) {\n return ImmutableMap.of();\n }\n String output = outputText.get();\n\n Optional agentOutputSchema = Optional.empty();\n if (agent instanceof LlmAgent llmAgent) {\n agentOutputSchema = llmAgent.outputSchema();\n }\n\n if (agentOutputSchema.isPresent()) {\n return SchemaUtils.validateOutputSchema(output, agentOutputSchema.get());\n } else {\n return ImmutableMap.of(\"result\", output);\n }\n });\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/mcp/McpTool.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools.mcp;\n\nimport static java.util.concurrent.TimeUnit.MILLISECONDS;\n\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.google.adk.JsonBaseModel;\nimport com.google.adk.tools.BaseTool;\nimport com.google.adk.tools.ToolContext;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.genai.types.FunctionDeclaration;\nimport com.google.genai.types.Schema;\nimport io.modelcontextprotocol.client.McpSyncClient;\nimport io.modelcontextprotocol.spec.McpSchema.CallToolRequest;\nimport io.modelcontextprotocol.spec.McpSchema.CallToolResult;\nimport io.modelcontextprotocol.spec.McpSchema.Content;\nimport io.modelcontextprotocol.spec.McpSchema.JsonSchema;\nimport io.modelcontextprotocol.spec.McpSchema.TextContent;\nimport io.modelcontextprotocol.spec.McpSchema.Tool;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\n\n// TODO(b/413489523): Add support for auth. This is a TODO for Python as well.\n/**\n * Initializes a MCP tool.\n *\n *

This wraps a MCP Tool interface and an active MCP Session. It invokes the MCP Tool through\n * executing the tool from remote MCP Session.\n */\npublic final class McpTool extends BaseTool {\n\n Tool mcpTool;\n McpSyncClient mcpSession;\n McpSessionManager mcpSessionManager;\n ObjectMapper objectMapper;\n\n /**\n * Creates a new McpTool with the default ObjectMapper.\n *\n * @param mcpTool The MCP tool to wrap.\n * @param mcpSession The MCP session to use to call the tool.\n * @param mcpSessionManager The MCP session manager to use to create new sessions.\n * @throws IllegalArgumentException If mcpTool or mcpSession are null.\n */\n public McpTool(Tool mcpTool, McpSyncClient mcpSession, McpSessionManager mcpSessionManager) {\n this(mcpTool, mcpSession, mcpSessionManager, JsonBaseModel.getMapper());\n }\n\n /**\n * Creates a new McpTool with the default ObjectMapper.\n *\n * @param mcpTool The MCP tool to wrap.\n * @param mcpSession The MCP session to use to call the tool.\n * @param mcpSessionManager The MCP session manager to use to create new sessions.\n * @param objectMapper The ObjectMapper to use to convert JSON schemas.\n * @throws IllegalArgumentException If mcpTool or mcpSession are null.\n */\n public McpTool(\n Tool mcpTool,\n McpSyncClient mcpSession,\n McpSessionManager mcpSessionManager,\n ObjectMapper objectMapper) {\n super(\n mcpTool == null ? \"\" : mcpTool.name(),\n mcpTool == null ? \"\" : (mcpTool.description().isEmpty() ? \"\" : mcpTool.description()));\n\n if (mcpTool == null) {\n throw new IllegalArgumentException(\"mcpTool cannot be null\");\n }\n if (mcpSession == null) {\n throw new IllegalArgumentException(\"mcpSession cannot be null\");\n }\n if (objectMapper == null) {\n throw new IllegalArgumentException(\"objectMapper cannot be null\");\n }\n this.mcpTool = mcpTool;\n this.mcpSession = mcpSession;\n this.mcpSessionManager = mcpSessionManager;\n this.objectMapper = objectMapper;\n }\n\n public Schema toGeminiSchema(JsonSchema openApiSchema) {\n return Schema.fromJson(objectMapper.valueToTree(openApiSchema).toString());\n }\n\n private void reintializeSession() {\n this.mcpSession = this.mcpSessionManager.createSession();\n }\n\n @Override\n public Optional declaration() {\n return Optional.of(\n FunctionDeclaration.builder()\n .name(this.name())\n .description(this.description())\n .parameters(toGeminiSchema(this.mcpTool.inputSchema()))\n .build());\n }\n\n @Override\n public Single> runAsync(Map args, ToolContext toolContext) {\n return Single.>fromCallable(\n () -> {\n CallToolResult callResult =\n mcpSession.callTool(new CallToolRequest(this.name(), ImmutableMap.copyOf(args)));\n\n if (callResult == null) {\n return ImmutableMap.of(\"error\", \"MCP framework error: CallToolResult was null\");\n }\n\n List contents = callResult.content();\n Boolean isToolError = callResult.isError();\n\n if (isToolError != null && isToolError) {\n String errorMessage = \"Tool execution failed.\";\n if (contents != null\n && !contents.isEmpty()\n && contents.get(0) instanceof TextContent) {\n TextContent textContent = (TextContent) contents.get(0);\n if (textContent.text() != null && !textContent.text().isEmpty()) {\n errorMessage += \" Details: \" + textContent.text();\n }\n }\n return ImmutableMap.of(\"error\", errorMessage);\n }\n\n if (contents == null || contents.isEmpty()) {\n return ImmutableMap.of();\n }\n\n List textOutputs = new ArrayList<>();\n for (Content content : contents) {\n if (content instanceof TextContent textContent) {\n if (textContent.text() != null) {\n textOutputs.add(textContent.text());\n }\n }\n }\n\n if (textOutputs.isEmpty()) {\n return ImmutableMap.of(\n \"error\",\n \"Tool '\" + this.name() + \"' returned content that is not TextContent.\",\n \"content_details\",\n contents.toString());\n }\n\n List> resultMaps = new ArrayList<>();\n for (String textOutput : textOutputs) {\n try {\n resultMaps.add(\n objectMapper.readValue(\n textOutput, new TypeReference>() {}));\n } catch (JsonProcessingException e) {\n resultMaps.add(ImmutableMap.of(\"text\", textOutput));\n }\n }\n return ImmutableMap.of(\"text_output\", resultMaps);\n })\n .retryWhen(\n errors ->\n errors\n .delay(100, MILLISECONDS)\n .take(3)\n .doOnNext(\n error -> {\n System.err.println(\"Retrying callTool due to: \" + error);\n reintializeSession();\n }));\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/models/Claude.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.models;\n\nimport com.anthropic.client.AnthropicClient;\nimport com.anthropic.models.messages.ContentBlock;\nimport com.anthropic.models.messages.ContentBlockParam;\nimport com.anthropic.models.messages.Message;\nimport com.anthropic.models.messages.MessageCreateParams;\nimport com.anthropic.models.messages.MessageParam;\nimport com.anthropic.models.messages.MessageParam.Role;\nimport com.anthropic.models.messages.TextBlockParam;\nimport com.anthropic.models.messages.Tool;\nimport com.anthropic.models.messages.ToolChoice;\nimport com.anthropic.models.messages.ToolChoiceAuto;\nimport com.anthropic.models.messages.ToolResultBlockParam;\nimport com.anthropic.models.messages.ToolUnion;\nimport com.anthropic.models.messages.ToolUseBlockParam;\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.fasterxml.jackson.datatype.jdk8.Jdk8Module;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.FunctionCall;\nimport com.google.genai.types.FunctionDeclaration;\nimport com.google.genai.types.GenerateContentConfig;\nimport com.google.genai.types.Part;\nimport io.reactivex.rxjava3.core.Flowable;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.Optional;\nimport java.util.stream.Collectors;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * Represents the Claude Generative AI model by Anthropic.\n *\n *

This class provides methods for interacting with Claude models. Streaming and live connections\n * are not currently supported for Claude.\n */\npublic class Claude extends BaseLlm {\n\n private static final Logger logger = LoggerFactory.getLogger(Claude.class);\n private static final int MAX_TOKEN = 8192;\n private final AnthropicClient anthropicClient;\n\n /**\n * Constructs a new Claude instance.\n *\n * @param modelName The name of the Claude model to use (e.g., \"claude-3-opus-20240229\").\n * @param anthropicClient The Anthropic API client instance.\n */\n public Claude(String modelName, AnthropicClient anthropicClient) {\n super(modelName);\n this.anthropicClient = anthropicClient;\n }\n\n @Override\n public Flowable generateContent(LlmRequest llmRequest, boolean stream) {\n // TODO: Switch to streaming API.\n List messages =\n llmRequest.contents().stream()\n .map(this::contentToAnthropicMessageParam)\n .collect(Collectors.toList());\n\n List tools = ImmutableList.of();\n if (llmRequest.config().isPresent()\n && llmRequest.config().get().tools().isPresent()\n && !llmRequest.config().get().tools().get().isEmpty()\n && llmRequest.config().get().tools().get().get(0).functionDeclarations().isPresent()) {\n tools =\n llmRequest.config().get().tools().get().get(0).functionDeclarations().get().stream()\n .map(this::functionDeclarationToAnthropicTool)\n .map(tool -> ToolUnion.ofTool(tool))\n .collect(Collectors.toList());\n }\n\n ToolChoice toolChoice =\n llmRequest.tools().isEmpty()\n ? null\n : ToolChoice.ofAuto(ToolChoiceAuto.builder().disableParallelToolUse(true).build());\n\n String systemText = \"\";\n Optional configOpt = llmRequest.config();\n if (configOpt.isPresent()) {\n Optional systemInstructionOpt = configOpt.get().systemInstruction();\n if (systemInstructionOpt.isPresent()) {\n String extractedSystemText =\n systemInstructionOpt.get().parts().orElse(ImmutableList.of()).stream()\n .filter(p -> p.text().isPresent())\n .map(p -> p.text().get())\n .collect(Collectors.joining(\"\\n\"));\n if (!extractedSystemText.isEmpty()) {\n systemText = extractedSystemText;\n }\n }\n }\n\n var message =\n this.anthropicClient\n .messages()\n .create(\n MessageCreateParams.builder()\n .model(llmRequest.model().orElse(model()))\n .system(systemText)\n .messages(messages)\n .tools(tools)\n .toolChoice(toolChoice)\n .maxTokens(MAX_TOKEN)\n .build());\n\n logger.debug(\"Claude response: {}\", message);\n\n return Flowable.just(convertAnthropicResponseToLlmResponse(message));\n }\n\n private Role toClaudeRole(String role) {\n return role.equals(\"model\") || role.equals(\"assistant\") ? Role.ASSISTANT : Role.USER;\n }\n\n private MessageParam contentToAnthropicMessageParam(Content content) {\n return MessageParam.builder()\n .role(toClaudeRole(content.role().orElse(\"\")))\n .contentOfBlockParams(\n content.parts().orElse(ImmutableList.of()).stream()\n .map(this::partToAnthropicMessageBlock)\n .filter(Objects::nonNull)\n .collect(Collectors.toList()))\n .build();\n }\n\n private ContentBlockParam partToAnthropicMessageBlock(Part part) {\n if (part.text().isPresent()) {\n return ContentBlockParam.ofText(TextBlockParam.builder().text(part.text().get()).build());\n } else if (part.functionCall().isPresent()) {\n return ContentBlockParam.ofToolUse(\n ToolUseBlockParam.builder()\n .id(part.functionCall().get().id().orElse(\"\"))\n .name(part.functionCall().get().name().orElseThrow())\n .type(com.anthropic.core.JsonValue.from(\"tool_use\"))\n .input(\n com.anthropic.core.JsonValue.from(\n part.functionCall().get().args().orElse(ImmutableMap.of())))\n .build());\n } else if (part.functionResponse().isPresent()) {\n String content = \"\";\n if (part.functionResponse().get().response().isPresent()\n && part.functionResponse().get().response().get().getOrDefault(\"result\", null) != null) {\n content = part.functionResponse().get().response().get().get(\"result\").toString();\n }\n return ContentBlockParam.ofToolResult(\n ToolResultBlockParam.builder()\n .toolUseId(part.functionResponse().get().id().orElse(\"\"))\n .content(content)\n .isError(false)\n .build());\n }\n throw new UnsupportedOperationException(\"Not supported yet.\");\n }\n\n private void updateTypeString(Map valueDict) {\n if (valueDict == null) {\n return;\n }\n if (valueDict.containsKey(\"type\")) {\n valueDict.put(\"type\", ((String) valueDict.get(\"type\")).toLowerCase());\n }\n\n if (valueDict.containsKey(\"items\")) {\n updateTypeString((Map) valueDict.get(\"items\"));\n\n if (valueDict.get(\"items\") instanceof Map\n && ((Map) valueDict.get(\"items\")).containsKey(\"properties\")) {\n Map properties =\n (Map) ((Map) valueDict.get(\"items\")).get(\"properties\");\n if (properties != null) {\n for (Object value : properties.values()) {\n if (value instanceof Map) {\n updateTypeString((Map) value);\n }\n }\n }\n }\n }\n }\n\n private Tool functionDeclarationToAnthropicTool(FunctionDeclaration functionDeclaration) {\n Map> properties = new HashMap<>();\n if (functionDeclaration.parameters().isPresent()\n && functionDeclaration.parameters().get().properties().isPresent()) {\n functionDeclaration\n .parameters()\n .get()\n .properties()\n .get()\n .forEach(\n (key, schema) -> {\n ObjectMapper objectMapper = new ObjectMapper();\n objectMapper.registerModule(new Jdk8Module());\n Map schemaMap =\n objectMapper.convertValue(schema, new TypeReference>() {});\n updateTypeString(schemaMap);\n properties.put(key, schemaMap);\n });\n }\n\n return Tool.builder()\n .name(functionDeclaration.name().orElseThrow())\n .description(functionDeclaration.description().orElse(\"\"))\n .inputSchema(\n Tool.InputSchema.builder()\n .properties(com.anthropic.core.JsonValue.from(properties))\n .build())\n .build();\n }\n\n private LlmResponse convertAnthropicResponseToLlmResponse(Message message) {\n LlmResponse.Builder responseBuilder = LlmResponse.builder();\n List parts = new ArrayList<>();\n\n if (message.content() != null) {\n for (ContentBlock block : message.content()) {\n Part part = anthropicContentBlockToPart(block);\n if (part != null) {\n parts.add(part);\n }\n }\n responseBuilder.content(\n Content.builder().role(\"model\").parts(ImmutableList.copyOf(parts)).build());\n }\n return responseBuilder.build();\n }\n\n private Part anthropicContentBlockToPart(ContentBlock block) {\n if (block.isText()) {\n return Part.builder().text(block.asText().text()).build();\n } else if (block.isToolUse()) {\n return Part.builder()\n .functionCall(\n FunctionCall.builder()\n .id(block.asToolUse().id())\n .name(block.asToolUse().name())\n .args(\n block\n .asToolUse()\n ._input()\n .convert(new TypeReference>() {}))\n .build())\n .build();\n }\n throw new UnsupportedOperationException(\"Not supported yet.\");\n }\n\n @Override\n public BaseLlmConnection connect(LlmRequest llmRequest) {\n throw new UnsupportedOperationException(\"Live connection is not supported for Claude models.\");\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/events/Event.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.events;\n\nimport static com.google.common.collect.ImmutableList.toImmutableList;\n\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonIgnore;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.databind.annotation.JsonDeserialize;\nimport com.google.adk.JsonBaseModel;\nimport com.google.common.collect.ImmutableList;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.FinishReason;\nimport com.google.genai.types.FunctionCall;\nimport com.google.genai.types.FunctionResponse;\nimport com.google.genai.types.GroundingMetadata;\nimport java.time.Instant;\nimport java.util.List;\nimport java.util.Objects;\nimport java.util.Optional;\nimport java.util.Set;\nimport java.util.UUID;\nimport javax.annotation.Nullable;\n\n// TODO - b/413761119 update Agent.java when resolved.\n/** Represents an event in a session. */\n@JsonDeserialize(builder = Event.Builder.class)\npublic class Event extends JsonBaseModel {\n\n private String id;\n private String invocationId;\n private String author;\n private Optional content = Optional.empty();\n private EventActions actions;\n private Optional> longRunningToolIds = Optional.empty();\n private Optional partial = Optional.empty();\n private Optional turnComplete = Optional.empty();\n private Optional errorCode = Optional.empty();\n private Optional errorMessage = Optional.empty();\n private Optional interrupted = Optional.empty();\n private Optional branch = Optional.empty();\n private Optional groundingMetadata = Optional.empty();\n private long timestamp;\n\n private Event() {}\n\n public static String generateEventId() {\n return UUID.randomUUID().toString();\n }\n\n /** The event id. */\n @JsonProperty(\"id\")\n public String id() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n /** Id of the invocation that this event belongs to. */\n @JsonProperty(\"invocationId\")\n public String invocationId() {\n return invocationId;\n }\n\n public void setInvocationId(String invocationId) {\n this.invocationId = invocationId;\n }\n\n /** The author of the event, it could be the name of the agent or \"user\" literal. */\n @JsonProperty(\"author\")\n public String author() {\n return author;\n }\n\n public void setAuthor(String author) {\n this.author = author;\n }\n\n @JsonProperty(\"content\")\n public Optional content() {\n return content;\n }\n\n public void setContent(Optional content) {\n this.content = content;\n }\n\n @JsonProperty(\"actions\")\n public EventActions actions() {\n return actions;\n }\n\n public void setActions(EventActions actions) {\n this.actions = actions;\n }\n\n /**\n * Set of ids of the long running function calls. Agent client will know from this field about\n * which function call is long running.\n */\n @JsonProperty(\"longRunningToolIds\")\n public Optional> longRunningToolIds() {\n return longRunningToolIds;\n }\n\n public void setLongRunningToolIds(Optional> longRunningToolIds) {\n this.longRunningToolIds = longRunningToolIds;\n }\n\n /**\n * partial is true for incomplete chunks from the LLM streaming response. The last chunk's partial\n * is False.\n */\n @JsonProperty(\"partial\")\n public Optional partial() {\n return partial;\n }\n\n public void setPartial(Optional partial) {\n this.partial = partial;\n }\n\n @JsonProperty(\"turnComplete\")\n public Optional turnComplete() {\n return turnComplete;\n }\n\n public void setTurnComplete(Optional turnComplete) {\n this.turnComplete = turnComplete;\n }\n\n @JsonProperty(\"errorCode\")\n public Optional errorCode() {\n return errorCode;\n }\n\n public void setErrorCode(Optional errorCode) {\n this.errorCode = errorCode;\n }\n\n @JsonProperty(\"errorMessage\")\n public Optional errorMessage() {\n return errorMessage;\n }\n\n public void setErrorMessage(Optional errorMessage) {\n this.errorMessage = errorMessage;\n }\n\n @JsonProperty(\"interrupted\")\n public Optional interrupted() {\n return interrupted;\n }\n\n public void setInterrupted(Optional interrupted) {\n this.interrupted = interrupted;\n }\n\n /**\n * The branch of the event. The format is like agent_1.agent_2.agent_3, where agent_1 is the\n * parent of agent_2, and agent_2 is the parent of agent_3. Branch is used when multiple sub-agent\n * shouldn't see their peer agents' conversation history.\n */\n @JsonProperty(\"branch\")\n public Optional branch() {\n return branch;\n }\n\n /**\n * Sets the branch for this event.\n *\n *

Format: agentA.agentB.agentC — shows hierarchy of nested agents.\n *\n * @param branch Branch identifier.\n */\n public void branch(@Nullable String branch) {\n this.branch = Optional.ofNullable(branch);\n }\n\n public void branch(Optional branch) {\n this.branch = branch;\n }\n\n /** The grounding metadata of the event. */\n @JsonProperty(\"groundingMetadata\")\n public Optional groundingMetadata() {\n return groundingMetadata;\n }\n\n public void setGroundingMetadata(Optional groundingMetadata) {\n this.groundingMetadata = groundingMetadata;\n }\n\n /** The timestamp of the event. */\n @JsonProperty(\"timestamp\")\n public long timestamp() {\n return timestamp;\n }\n\n public void setTimestamp(long timestamp) {\n this.timestamp = timestamp;\n }\n\n /** Returns all function calls from this event. */\n @JsonIgnore\n public final ImmutableList functionCalls() {\n return content().flatMap(Content::parts).stream()\n .flatMap(List::stream)\n .flatMap(part -> part.functionCall().stream())\n .collect(toImmutableList());\n }\n\n /** Returns all function responses from this event. */\n @JsonIgnore\n public final ImmutableList functionResponses() {\n return content().flatMap(Content::parts).stream()\n .flatMap(List::stream)\n .flatMap(part -> part.functionResponse().stream())\n .collect(toImmutableList());\n }\n\n /** Returns true if this is a final response. */\n @JsonIgnore\n public final boolean finalResponse() {\n if (actions().skipSummarization().orElse(false)\n || (longRunningToolIds().isPresent() && !longRunningToolIds().get().isEmpty())) {\n return true;\n }\n return functionCalls().isEmpty() && functionResponses().isEmpty() && !partial().orElse(false);\n }\n\n /**\n * Converts the event content into a readable string.\n *\n *

Includes text, function calls, and responses.\n *\n * @return Stringified content.\n */\n public final String stringifyContent() {\n StringBuilder sb = new StringBuilder();\n content().flatMap(Content::parts).stream()\n .flatMap(List::stream)\n .forEach(\n part -> {\n part.text().ifPresent(sb::append);\n part.functionCall()\n .ifPresent(functionCall -> sb.append(\"Function Call: \").append(functionCall));\n part.functionResponse()\n .ifPresent(\n functionResponse ->\n sb.append(\"Function Response: \").append(functionResponse));\n });\n return sb.toString();\n }\n\n /** Builder for {@link Event}. */\n public static class Builder {\n\n private String id;\n private String invocationId;\n private String author;\n private Optional content = Optional.empty();\n private EventActions actions;\n private Optional> longRunningToolIds = Optional.empty();\n private Optional partial = Optional.empty();\n private Optional turnComplete = Optional.empty();\n private Optional errorCode = Optional.empty();\n private Optional errorMessage = Optional.empty();\n private Optional interrupted = Optional.empty();\n private Optional branch = Optional.empty();\n private Optional groundingMetadata = Optional.empty();\n private Optional timestamp = Optional.empty();\n\n @JsonCreator\n private static Builder create() {\n return new Builder();\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"id\")\n public Builder id(String value) {\n this.id = value;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"invocationId\")\n public Builder invocationId(String value) {\n this.invocationId = value;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"author\")\n public Builder author(String value) {\n this.author = value;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"content\")\n public Builder content(@Nullable Content value) {\n this.content = Optional.ofNullable(value);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder content(Optional value) {\n this.content = value;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"actions\")\n public Builder actions(EventActions value) {\n this.actions = value;\n return this;\n }\n\n Optional actions() {\n return Optional.ofNullable(actions);\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"longRunningToolIds\")\n public Builder longRunningToolIds(@Nullable Set value) {\n this.longRunningToolIds = Optional.ofNullable(value);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder longRunningToolIds(Optional> value) {\n this.longRunningToolIds = value;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"partial\")\n public Builder partial(@Nullable Boolean value) {\n this.partial = Optional.ofNullable(value);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder partial(Optional value) {\n this.partial = value;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"turnComplete\")\n public Builder turnComplete(@Nullable Boolean value) {\n this.turnComplete = Optional.ofNullable(value);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder turnComplete(Optional value) {\n this.turnComplete = value;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"errorCode\")\n public Builder errorCode(@Nullable FinishReason value) {\n this.errorCode = Optional.ofNullable(value);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder errorCode(Optional value) {\n this.errorCode = value;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"errorMessage\")\n public Builder errorMessage(@Nullable String value) {\n this.errorMessage = Optional.ofNullable(value);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder errorMessage(Optional value) {\n this.errorMessage = value;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"interrupted\")\n public Builder interrupted(@Nullable Boolean value) {\n this.interrupted = Optional.ofNullable(value);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder interrupted(Optional value) {\n this.interrupted = value;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"timestamp\")\n public Builder timestamp(long value) {\n this.timestamp = Optional.of(value);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder timestamp(Optional value) {\n this.timestamp = value;\n return this;\n }\n\n // Getter for builder's timestamp, used in build()\n Optional timestamp() {\n return timestamp;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"branch\")\n public Builder branch(@Nullable String value) {\n this.branch = Optional.ofNullable(value);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder branch(Optional value) {\n this.branch = value;\n return this;\n }\n\n // Getter for builder's branch, used in build()\n Optional branch() {\n return branch;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"groundingMetadata\")\n public Builder groundingMetadata(@Nullable GroundingMetadata value) {\n this.groundingMetadata = Optional.ofNullable(value);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder groundingMetadata(Optional value) {\n this.groundingMetadata = value;\n return this;\n }\n\n Optional groundingMetadata() {\n return groundingMetadata;\n }\n\n public Event build() {\n Event event = new Event();\n event.setId(id);\n event.setInvocationId(invocationId);\n event.setAuthor(author);\n event.setContent(content);\n event.setLongRunningToolIds(longRunningToolIds);\n event.setPartial(partial);\n event.setTurnComplete(turnComplete);\n event.setErrorCode(errorCode);\n event.setErrorMessage(errorMessage);\n event.setInterrupted(interrupted);\n event.branch(branch);\n event.setGroundingMetadata(groundingMetadata);\n\n event.setActions(actions().orElse(EventActions.builder().build()));\n event.setTimestamp(timestamp().orElse(Instant.now().toEpochMilli()));\n return event;\n }\n }\n\n public static Builder builder() {\n return new Builder();\n }\n\n /** Parses an event from a JSON string. */\n public static Event fromJson(String json) {\n return fromJsonString(json, Event.class);\n }\n\n /** Creates a builder pre-filled with this event's values. */\n public Builder toBuilder() {\n Builder builder =\n new Builder()\n .id(this.id)\n .invocationId(this.invocationId)\n .author(this.author)\n .content(this.content)\n .actions(this.actions)\n .longRunningToolIds(this.longRunningToolIds)\n .partial(this.partial)\n .turnComplete(this.turnComplete)\n .errorCode(this.errorCode)\n .errorMessage(this.errorMessage)\n .interrupted(this.interrupted)\n .branch(this.branch)\n .groundingMetadata(this.groundingMetadata);\n if (this.timestamp != 0) {\n builder.timestamp(this.timestamp);\n }\n return builder;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (!(obj instanceof Event other)) {\n return false;\n }\n return timestamp == other.timestamp\n && Objects.equals(id, other.id)\n && Objects.equals(invocationId, other.invocationId)\n && Objects.equals(author, other.author)\n && Objects.equals(content, other.content)\n && Objects.equals(actions, other.actions)\n && Objects.equals(longRunningToolIds, other.longRunningToolIds)\n && Objects.equals(partial, other.partial)\n && Objects.equals(turnComplete, other.turnComplete)\n && Objects.equals(errorCode, other.errorCode)\n && Objects.equals(errorMessage, other.errorMessage)\n && Objects.equals(interrupted, other.interrupted)\n && Objects.equals(branch, other.branch)\n && Objects.equals(groundingMetadata, other.groundingMetadata);\n }\n\n @Override\n public String toString() {\n return toJson();\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(\n id,\n invocationId,\n author,\n content,\n actions,\n longRunningToolIds,\n partial,\n turnComplete,\n errorCode,\n errorMessage,\n interrupted,\n branch,\n groundingMetadata,\n timestamp);\n }\n}\n"], ["/adk-java/dev/src/main/java/com/google/adk/web/AgentCompilerLoader.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.web;\n\nimport com.google.adk.agents.BaseAgent;\nimport com.google.adk.web.config.AgentLoadingProperties;\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.PrintWriter;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Modifier;\nimport java.net.URISyntaxException;\nimport java.net.URL;\nimport java.net.URLClassLoader;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.nio.file.StandardCopyOption;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.LinkedHashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\nimport org.eclipse.jdt.core.compiler.batch.BatchCompiler;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.stereotype.Service;\n\n/**\n * Dynamically compiles and loads ADK {@link BaseAgent} implementations from source files. It\n * orchestrates the discovery of the ADK core JAR, compilation of agent sources using the Eclipse\n * JDT (ECJ) compiler, and loading of compiled agents into isolated classloaders. Agents are\n * identified by a public static field named {@code ROOT_AGENT}. Supports agent organization in\n * subdirectories or as individual {@code .java} files.\n */\n@Service\npublic class AgentCompilerLoader {\n private static final Logger logger = LoggerFactory.getLogger(AgentCompilerLoader.class);\n private final AgentLoadingProperties properties;\n private Path compiledAgentsOutputDir;\n private final String adkCoreJarPathForCompilation;\n\n /**\n * Initializes the loader with agent configuration and proactively attempts to locate the ADK core\n * JAR. This JAR, containing {@link BaseAgent} and other core ADK types, is crucial for agent\n * compilation. The location strategy (see {@link #locateAndPrepareAdkCoreJar()}) includes\n * handling directly available JARs and extracting nested JARs (e.g., in Spring Boot fat JARs) to\n * ensure it's available for the compilation classpath.\n *\n * @param properties Configuration detailing agent source locations and compilation settings.\n */\n public AgentCompilerLoader(AgentLoadingProperties properties) {\n this.properties = properties;\n this.adkCoreJarPathForCompilation = locateAndPrepareAdkCoreJar();\n }\n\n /**\n * Attempts to find the ADK core JAR, which provides {@link BaseAgent} and essential ADK classes\n * required for compiling dynamically loaded agents.\n *\n *

Strategies include:\n *\n *

    \n *
  • Checking if {@code BaseAgent.class} is loaded from a plain {@code .jar} file on the\n * classpath.\n *
  • Detecting and extracting the ADK core JAR if it's nested within a \"fat JAR\" (e.g., {@code\n * BOOT-INF/lib/} in Spring Boot applications). The extracted JAR is placed in a temporary\n * file for use during compilation.\n *
\n *\n * If located, its absolute path is returned for explicit inclusion in the compiler's classpath.\n * Returns an empty string if the JAR cannot be reliably pinpointed through these specific means,\n * in which case compilation will rely on broader classpath introspection.\n *\n * @return Absolute path to the ADK core JAR if found and prepared, otherwise an empty string.\n */\n private String locateAndPrepareAdkCoreJar() {\n try {\n URL agentClassUrl = BaseAgent.class.getProtectionDomain().getCodeSource().getLocation();\n if (agentClassUrl == null) {\n logger.warn(\"Could not get location for BaseAgent.class. ADK Core JAR might not be found.\");\n return \"\";\n }\n logger.debug(\"BaseAgent.class loaded from: {}\", agentClassUrl);\n\n if (\"file\".equals(agentClassUrl.getProtocol())) {\n Path path = Paths.get(agentClassUrl.toURI());\n if (path.toString().endsWith(\".jar\") && Files.exists(path)) {\n logger.debug(\n \"ADK Core JAR (or where BaseAgent resides) found directly on classpath: {}\",\n path.toAbsolutePath());\n return path.toAbsolutePath().toString();\n } else if (Files.isDirectory(path)) {\n logger.debug(\n \"BaseAgent.class found in directory (e.g., target/classes): {}. This path will be\"\n + \" part of classloader introspection.\",\n path.toAbsolutePath());\n return \"\";\n }\n } else if (\"jar\".equals(agentClassUrl.getProtocol())) { // Typically for nested JARs\n String urlPath = agentClassUrl.getPath();\n if (urlPath.startsWith(\"file:\")) {\n urlPath = urlPath.substring(\"file:\".length());\n }\n int firstSeparator = urlPath.indexOf(\"!/\");\n if (firstSeparator == -1) {\n logger.warn(\"Malformed JAR URL for BaseAgent.class: {}\", agentClassUrl);\n return \"\";\n }\n\n String mainJarPath = urlPath.substring(0, firstSeparator);\n String nestedPath = urlPath.substring(firstSeparator);\n\n if (nestedPath.startsWith(\"!/BOOT-INF/lib/\") && nestedPath.contains(\"google-adk-\")) {\n int nestedJarStartInPath = \"!/BOOT-INF/lib/\".length();\n int nestedJarEndInPath = nestedPath.indexOf(\"!/\", nestedJarStartInPath);\n if (nestedJarEndInPath > 0) {\n String nestedJarName = nestedPath.substring(nestedJarStartInPath, nestedJarEndInPath);\n String nestedJarUrlString =\n \"jar:file:\" + mainJarPath + \"!/BOOT-INF/lib/\" + nestedJarName;\n\n Path tempFile = Files.createTempFile(\"adk-core-extracted-\", \".jar\");\n try (InputStream is = new URL(nestedJarUrlString).openStream()) {\n Files.copy(is, tempFile, StandardCopyOption.REPLACE_EXISTING);\n }\n tempFile.toFile().deleteOnExit();\n logger.debug(\n \"Extracted ADK Core JAR '{}' from nested location to: {}\",\n nestedJarName,\n tempFile.toAbsolutePath());\n return tempFile.toAbsolutePath().toString();\n }\n } else if (mainJarPath.contains(\"google-adk-\") && mainJarPath.endsWith(\".jar\")) {\n File adkJar = new File(mainJarPath);\n if (adkJar.exists()) {\n logger.debug(\"ADK Core JAR identified as the outer JAR: {}\", adkJar.getAbsolutePath());\n return adkJar.getAbsolutePath();\n }\n }\n }\n } catch (Exception e) {\n logger.error(\"Error trying to locate or extract ADK Core JAR\", e);\n }\n logger.warn(\n \"ADK Core JAR could not be reliably located for compilation via locateAndPrepareAdkCoreJar.\"\n + \" Relying on classloader introspection.\");\n return \"\";\n }\n\n /**\n * Discovers, compiles, and loads agents from the configured source directory.\n *\n *

The process for each potential \"agent unit\" (a subdirectory or a root {@code .java} file):\n *\n *

    \n *
  1. Collects {@code .java} source files.\n *
  2. Compiles these sources using ECJ (see {@link #compileSourcesWithECJ(List, Path)}) into a\n * temporary, unit-specific output directory. This directory is cleaned up on JVM exit.\n *
  3. Creates a dedicated {@link URLClassLoader} for the compiled unit, isolating its classes.\n *
  4. Scans compiled classes for a public static field {@code ROOT_AGENT} assignable to {@link\n * BaseAgent}. This field serves as the designated entry point for an agent.\n *
  5. Instantiates and stores the {@link BaseAgent} if found, keyed by its name.\n *
\n *\n * This approach allows for dynamic addition of agents without pre-compilation and supports\n * independent classpaths per agent unit if needed (though current implementation uses a shared\n * parent classloader).\n *\n * @return A map of successfully loaded agent names to their {@link BaseAgent} instances. Returns\n * an empty map if the source directory isn't configured or no agents are found.\n * @throws IOException If an I/O error occurs (e.g., creating temp directories, reading sources).\n */\n public Map loadAgents() throws IOException {\n if (properties.getSourceDir() == null || properties.getSourceDir().isEmpty()) {\n logger.info(\n \"Agent source directory (adk.agents.source-dir) not configured. No dynamic agents will be\"\n + \" loaded.\");\n return Collections.emptyMap();\n }\n\n Path agentsSourceRoot = Paths.get(properties.getSourceDir());\n if (!Files.isDirectory(agentsSourceRoot)) {\n logger.warn(\"Agent source directory does not exist: {}\", agentsSourceRoot);\n return Collections.emptyMap();\n }\n\n this.compiledAgentsOutputDir = Files.createTempDirectory(\"adk-compiled-agents-\");\n this.compiledAgentsOutputDir.toFile().deleteOnExit();\n logger.debug(\"Compiling agents from {} to {}\", agentsSourceRoot, compiledAgentsOutputDir);\n\n Map loadedAgents = new HashMap<>();\n\n try (Stream stream = Files.list(agentsSourceRoot)) {\n List entries = stream.collect(Collectors.toList());\n\n for (Path entry : entries) {\n List javaFilesToCompile = new ArrayList<>();\n String agentUnitName;\n\n if (Files.isDirectory(entry)) {\n agentUnitName = entry.getFileName().toString();\n logger.debug(\"Processing agent sources from directory: {}\", agentUnitName);\n try (Stream javaFilesStream =\n Files.walk(entry)\n .filter(p -> p.toString().endsWith(\".java\") && Files.isRegularFile(p))) {\n javaFilesToCompile =\n javaFilesStream\n .map(p -> p.toAbsolutePath().toString())\n .collect(Collectors.toList());\n }\n } else if (Files.isRegularFile(entry) && entry.getFileName().toString().endsWith(\".java\")) {\n String fileName = entry.getFileName().toString();\n agentUnitName = fileName.substring(0, fileName.length() - \".java\".length());\n logger.debug(\"Processing agent source file: {}\", entry.getFileName());\n javaFilesToCompile.add(entry.toAbsolutePath().toString());\n } else {\n logger.trace(\"Skipping non-agent entry in agent source root: {}\", entry.getFileName());\n continue;\n }\n\n if (javaFilesToCompile.isEmpty()) {\n logger.debug(\"No .java files found for agent unit: {}\", agentUnitName);\n continue;\n }\n\n Path unitSpecificOutputDir = compiledAgentsOutputDir.resolve(agentUnitName);\n Files.createDirectories(unitSpecificOutputDir);\n\n boolean compilationSuccess =\n compileSourcesWithECJ(javaFilesToCompile, unitSpecificOutputDir);\n\n if (compilationSuccess) {\n try {\n List classLoaderUrls = new ArrayList<>();\n classLoaderUrls.add(unitSpecificOutputDir.toUri().toURL());\n\n URLClassLoader agentClassLoader =\n new URLClassLoader(\n classLoaderUrls.toArray(new URL[0]),\n AgentCompilerLoader.class.getClassLoader());\n\n Files.walk(unitSpecificOutputDir)\n .filter(p -> p.toString().endsWith(\".class\"))\n .forEach(\n classFile -> {\n try {\n String relativePath =\n unitSpecificOutputDir.relativize(classFile).toString();\n String className =\n relativePath\n .substring(0, relativePath.length() - \".class\".length())\n .replace(File.separatorChar, '.');\n\n Class loadedClass = agentClassLoader.loadClass(className);\n Field rootAgentField = null;\n try {\n rootAgentField = loadedClass.getField(\"ROOT_AGENT\");\n } catch (NoSuchFieldException e) {\n return;\n }\n\n if (Modifier.isStatic(rootAgentField.getModifiers())\n && BaseAgent.class.isAssignableFrom(rootAgentField.getType())) {\n BaseAgent agentInstance = (BaseAgent) rootAgentField.get(null);\n if (agentInstance != null) {\n if (loadedAgents.containsKey(agentInstance.name())) {\n logger.warn(\n \"Found another agent with name {}. This will overwrite the\"\n + \" original agent loaded with this name from unit {} using\"\n + \" class {}\",\n agentInstance.name(),\n agentUnitName,\n className);\n }\n loadedAgents.put(agentInstance.name(), agentInstance);\n logger.debug(\n \"Successfully loaded agent '{}' from unit: {} using class {}\",\n agentInstance.name(),\n agentUnitName,\n className);\n } else {\n logger.warn(\n \"ROOT_AGENT field in class {} from unit {} was null\",\n className,\n agentUnitName);\n }\n }\n } catch (ClassNotFoundException | IllegalAccessException e) {\n logger.error(\n \"Error loading or accessing agent from class file {} for unit {}\",\n classFile,\n agentUnitName,\n e);\n } catch (Exception e) {\n logger.error(\n \"Unexpected error processing class file {} for unit {}\",\n classFile,\n agentUnitName,\n e);\n }\n });\n } catch (Exception e) {\n logger.error(\n \"Error during class loading setup for unit {}: {}\",\n agentUnitName,\n e.getMessage(),\n e);\n }\n } else {\n logger.error(\"Compilation failed for agent unit: {}\", agentUnitName);\n }\n }\n }\n return loadedAgents;\n }\n\n /**\n * Compiles the given Java source files using the Eclipse JDT (ECJ) batch compiler.\n *\n *

Key aspects of the compilation process:\n *\n *

    \n *
  • Sets Java version to 17 (to align with core ADK library) and suppresses warnings by\n * default.\n *
  • Constructs the compilation classpath by:\n *
      \n *
    1. Introspecting the current classloader hierarchy ({@link URLClassLoader} instances)\n * to gather available JARs and class directories.\n *
    2. Falling back to {@code System.getProperty(\"java.class.path\")} if introspection\n * yields no results.\n *
    3. Explicitly adding the ADK Core JAR path (determined by {@link\n * #locateAndPrepareAdkCoreJar()}) to ensure {@link BaseAgent} and related types are\n * resolvable.\n *
    4. Appending any user-defined classpath entries from {@link\n * AgentLoadingProperties#getCompileClasspath()}.\n *
    \n *
  • Outputs compiled {@code .class} files to the specified {@code outputDir}.\n *
\n *\n * This method aims to provide a robust classpath for compiling agents in various runtime\n * environments, including IDEs, standard Java executions, and fat JAR deployments.\n *\n * @param javaFilePaths A list of absolute paths to {@code .java} files to be compiled.\n * @param outputDir The directory where compiled {@code .class} files will be placed.\n * @return {@code true} if compilation succeeds, {@code false} otherwise.\n */\n private boolean compileSourcesWithECJ(List javaFilePaths, Path outputDir) {\n List ecjArgs = new ArrayList<>();\n ecjArgs.add(\"-17\"); // Java version\n ecjArgs.add(\"-nowarn\");\n ecjArgs.add(\"-d\");\n ecjArgs.add(outputDir.toAbsolutePath().toString());\n\n Set classpathEntries = new LinkedHashSet<>();\n\n logger.debug(\"Attempting to derive ECJ classpath from classloader hierarchy...\");\n ClassLoader currentClassLoader = AgentCompilerLoader.class.getClassLoader();\n int classLoaderCount = 0;\n while (currentClassLoader != null) {\n classLoaderCount++;\n logger.debug(\n \"Inspecting classloader ({}) : {}\",\n classLoaderCount,\n currentClassLoader.getClass().getName());\n if (currentClassLoader instanceof java.net.URLClassLoader) {\n URL[] urls = ((java.net.URLClassLoader) currentClassLoader).getURLs();\n logger.debug(\n \" Found {} URLs in URLClassLoader {}\",\n urls.length,\n currentClassLoader.getClass().getName());\n for (URL url : urls) {\n try {\n if (\"file\".equals(url.getProtocol())) {\n String path = Paths.get(url.toURI()).toString();\n classpathEntries.add(path);\n logger.trace(\" Added to ECJ classpath: {}\", path);\n } else {\n logger.debug(\n \" Skipping non-file URL from classloader {}: {}\",\n currentClassLoader.getClass().getName(),\n url);\n }\n } catch (URISyntaxException | IllegalArgumentException e) {\n logger.warn(\n \" Could not convert URL to path or add to classpath from {}: {} (Error: {})\",\n currentClassLoader.getClass().getName(),\n url,\n e.getMessage());\n } catch (Exception e) {\n logger.warn(\n \" Unexpected error converting URL to path from {}: {} (Error: {})\",\n currentClassLoader.getClass().getName(),\n url,\n e.getMessage(),\n e);\n }\n }\n }\n currentClassLoader = currentClassLoader.getParent();\n }\n\n if (classpathEntries.isEmpty()) {\n logger.warn(\n \"No classpath entries derived from classloader hierarchy. \"\n + \"Falling back to System.getProperty(\\\"java.class.path\\\").\");\n String systemClasspath = System.getProperty(\"java.class.path\");\n if (systemClasspath != null && !systemClasspath.isEmpty()) {\n logger.debug(\"Using system classpath for ECJ (fallback): {}\", systemClasspath);\n classpathEntries.addAll(Arrays.asList(systemClasspath.split(File.pathSeparator)));\n } else {\n logger.error(\"System classpath (java.class.path) is also null or empty.\");\n }\n }\n\n if (this.adkCoreJarPathForCompilation != null && !this.adkCoreJarPathForCompilation.isEmpty()) {\n if (!classpathEntries.contains(this.adkCoreJarPathForCompilation)) {\n logger.debug(\n \"Adding ADK Core JAR path explicitly to ECJ classpath: {}\",\n this.adkCoreJarPathForCompilation);\n classpathEntries.add(this.adkCoreJarPathForCompilation);\n } else {\n logger.debug(\n \"ADK Core JAR path ({}) already found in derived ECJ classpath.\",\n this.adkCoreJarPathForCompilation);\n }\n } else if (classpathEntries.stream().noneMatch(p -> p.contains(\"google-adk\"))) {\n logger.error(\n \"ADK Core JAR path is missing and no 'google-adk' JAR found in derived classpath. \"\n + \"Compilation will likely fail to find BaseAgent.\");\n }\n\n if (properties.getCompileClasspath() != null && !properties.getCompileClasspath().isEmpty()) {\n String userClasspath = properties.getCompileClasspath();\n logger.info(\n \"Appending user-defined classpath (adk.agents.compile-classpath) to ECJ: {}\",\n userClasspath);\n classpathEntries.addAll(Arrays.asList(userClasspath.split(File.pathSeparator)));\n }\n\n if (!classpathEntries.isEmpty()) {\n String effectiveClasspath =\n classpathEntries.stream().collect(Collectors.joining(File.pathSeparator));\n ecjArgs.add(\"-cp\");\n ecjArgs.add(effectiveClasspath);\n logger.debug(\"Constructed ECJ classpath with {} entries\", classpathEntries.size());\n logger.debug(\"Final effective ECJ classpath: {}\", effectiveClasspath);\n } else {\n logger.error(\"ECJ Classpath is empty after all attempts. Compilation will fail.\");\n return false;\n }\n\n ecjArgs.addAll(javaFilePaths);\n\n logger.debug(\"ECJ Args: {}\", String.join(\" \", ecjArgs));\n\n PrintWriter outWriter = new PrintWriter(System.out, true);\n PrintWriter errWriter = new PrintWriter(System.err, true);\n\n boolean success =\n BatchCompiler.compile(ecjArgs.toArray(new String[0]), outWriter, errWriter, null);\n if (!success) {\n logger.error(\"ECJ Compilation failed. See console output for details.\");\n }\n return success;\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/agents/LlmAgent.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.agents;\n\nimport static java.util.stream.Collectors.joining;\n\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.google.adk.SchemaUtils;\nimport com.google.adk.agents.Callbacks.AfterAgentCallback;\nimport com.google.adk.agents.Callbacks.AfterAgentCallbackBase;\nimport com.google.adk.agents.Callbacks.AfterAgentCallbackSync;\nimport com.google.adk.agents.Callbacks.AfterModelCallback;\nimport com.google.adk.agents.Callbacks.AfterModelCallbackBase;\nimport com.google.adk.agents.Callbacks.AfterModelCallbackSync;\nimport com.google.adk.agents.Callbacks.AfterToolCallback;\nimport com.google.adk.agents.Callbacks.AfterToolCallbackBase;\nimport com.google.adk.agents.Callbacks.AfterToolCallbackSync;\nimport com.google.adk.agents.Callbacks.BeforeAgentCallback;\nimport com.google.adk.agents.Callbacks.BeforeAgentCallbackBase;\nimport com.google.adk.agents.Callbacks.BeforeAgentCallbackSync;\nimport com.google.adk.agents.Callbacks.BeforeModelCallback;\nimport com.google.adk.agents.Callbacks.BeforeModelCallbackBase;\nimport com.google.adk.agents.Callbacks.BeforeModelCallbackSync;\nimport com.google.adk.agents.Callbacks.BeforeToolCallback;\nimport com.google.adk.agents.Callbacks.BeforeToolCallbackBase;\nimport com.google.adk.agents.Callbacks.BeforeToolCallbackSync;\nimport com.google.adk.events.Event;\nimport com.google.adk.examples.BaseExampleProvider;\nimport com.google.adk.examples.Example;\nimport com.google.adk.flows.llmflows.AutoFlow;\nimport com.google.adk.flows.llmflows.BaseLlmFlow;\nimport com.google.adk.flows.llmflows.SingleFlow;\nimport com.google.adk.models.BaseLlm;\nimport com.google.adk.models.Model;\nimport com.google.adk.tools.BaseTool;\nimport com.google.adk.tools.BaseToolset;\nimport com.google.common.base.Preconditions;\nimport com.google.common.collect.ImmutableList;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.GenerateContentConfig;\nimport com.google.genai.types.Schema;\nimport io.reactivex.rxjava3.core.Flowable;\nimport io.reactivex.rxjava3.core.Maybe;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.concurrent.Executor;\nimport javax.annotation.Nullable;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/** The LLM-based agent. */\npublic class LlmAgent extends BaseAgent {\n\n private static final Logger logger = LoggerFactory.getLogger(LlmAgent.class);\n\n /**\n * Enum to define if contents of previous events should be included in requests to the underlying\n * LLM.\n */\n public enum IncludeContents {\n DEFAULT,\n NONE\n }\n\n private final Optional model;\n private final Instruction instruction;\n private final Instruction globalInstruction;\n private final List toolsUnion;\n private final Optional generateContentConfig;\n private final Optional exampleProvider;\n private final IncludeContents includeContents;\n\n private final boolean planning;\n private final Optional maxSteps;\n private final boolean disallowTransferToParent;\n private final boolean disallowTransferToPeers;\n private final Optional> beforeModelCallback;\n private final Optional> afterModelCallback;\n private final Optional> beforeToolCallback;\n private final Optional> afterToolCallback;\n private final Optional inputSchema;\n private final Optional outputSchema;\n private final Optional executor;\n private final Optional outputKey;\n\n private volatile Model resolvedModel;\n private final BaseLlmFlow llmFlow;\n\n protected LlmAgent(Builder builder) {\n super(\n builder.name,\n builder.description,\n builder.subAgents,\n builder.beforeAgentCallback,\n builder.afterAgentCallback);\n this.model = Optional.ofNullable(builder.model);\n this.instruction =\n builder.instruction == null ? new Instruction.Static(\"\") : builder.instruction;\n this.globalInstruction =\n builder.globalInstruction == null ? new Instruction.Static(\"\") : builder.globalInstruction;\n this.generateContentConfig = Optional.ofNullable(builder.generateContentConfig);\n this.exampleProvider = Optional.ofNullable(builder.exampleProvider);\n this.includeContents =\n builder.includeContents != null ? builder.includeContents : IncludeContents.DEFAULT;\n this.planning = builder.planning != null && builder.planning;\n this.maxSteps = Optional.ofNullable(builder.maxSteps);\n this.disallowTransferToParent = builder.disallowTransferToParent;\n this.disallowTransferToPeers = builder.disallowTransferToPeers;\n this.beforeModelCallback = Optional.ofNullable(builder.beforeModelCallback);\n this.afterModelCallback = Optional.ofNullable(builder.afterModelCallback);\n this.beforeToolCallback = Optional.ofNullable(builder.beforeToolCallback);\n this.afterToolCallback = Optional.ofNullable(builder.afterToolCallback);\n this.inputSchema = Optional.ofNullable(builder.inputSchema);\n this.outputSchema = Optional.ofNullable(builder.outputSchema);\n this.executor = Optional.ofNullable(builder.executor);\n this.outputKey = Optional.ofNullable(builder.outputKey);\n this.toolsUnion = builder.toolsUnion != null ? builder.toolsUnion : ImmutableList.of();\n\n this.llmFlow = determineLlmFlow();\n\n // Validate name not empty.\n Preconditions.checkArgument(!this.name().isEmpty(), \"Agent name cannot be empty.\");\n }\n\n /** Returns a {@link Builder} for {@link LlmAgent}. */\n public static Builder builder() {\n return new Builder();\n }\n\n /** Builder for {@link LlmAgent}. */\n public static class Builder {\n private String name;\n private String description;\n\n private Model model;\n\n private Instruction instruction;\n private Instruction globalInstruction;\n private ImmutableList subAgents;\n private ImmutableList toolsUnion;\n private GenerateContentConfig generateContentConfig;\n private BaseExampleProvider exampleProvider;\n private IncludeContents includeContents;\n private Boolean planning;\n private Integer maxSteps;\n private Boolean disallowTransferToParent;\n private Boolean disallowTransferToPeers;\n private ImmutableList beforeModelCallback;\n private ImmutableList afterModelCallback;\n private ImmutableList beforeAgentCallback;\n private ImmutableList afterAgentCallback;\n private ImmutableList beforeToolCallback;\n private ImmutableList afterToolCallback;\n private Schema inputSchema;\n private Schema outputSchema;\n private Executor executor;\n private String outputKey;\n\n @CanIgnoreReturnValue\n public Builder name(String name) {\n this.name = name;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder description(String description) {\n this.description = description;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder model(String model) {\n this.model = Model.builder().modelName(model).build();\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder model(BaseLlm model) {\n this.model = Model.builder().model(model).build();\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder instruction(Instruction instruction) {\n this.instruction = instruction;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder instruction(String instruction) {\n this.instruction = (instruction == null) ? null : new Instruction.Static(instruction);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder globalInstruction(Instruction globalInstruction) {\n this.globalInstruction = globalInstruction;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder globalInstruction(String globalInstruction) {\n this.globalInstruction =\n (globalInstruction == null) ? null : new Instruction.Static(globalInstruction);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder subAgents(List subAgents) {\n this.subAgents = ImmutableList.copyOf(subAgents);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder subAgents(BaseAgent... subAgents) {\n this.subAgents = ImmutableList.copyOf(subAgents);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder tools(List tools) {\n this.toolsUnion = ImmutableList.copyOf(tools);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder tools(Object... tools) {\n this.toolsUnion = ImmutableList.copyOf(tools);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder generateContentConfig(GenerateContentConfig generateContentConfig) {\n this.generateContentConfig = generateContentConfig;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder exampleProvider(BaseExampleProvider exampleProvider) {\n this.exampleProvider = exampleProvider;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder exampleProvider(List examples) {\n this.exampleProvider =\n new BaseExampleProvider() {\n @Override\n public List getExamples(String query) {\n return examples;\n }\n };\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder exampleProvider(Example... examples) {\n this.exampleProvider =\n new BaseExampleProvider() {\n @Override\n public ImmutableList getExamples(String query) {\n return ImmutableList.copyOf(examples);\n }\n };\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder includeContents(IncludeContents includeContents) {\n this.includeContents = includeContents;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder planning(boolean planning) {\n this.planning = planning;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder maxSteps(int maxSteps) {\n this.maxSteps = maxSteps;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder disallowTransferToParent(boolean disallowTransferToParent) {\n this.disallowTransferToParent = disallowTransferToParent;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder disallowTransferToPeers(boolean disallowTransferToPeers) {\n this.disallowTransferToPeers = disallowTransferToPeers;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeModelCallback(BeforeModelCallback beforeModelCallback) {\n this.beforeModelCallback = ImmutableList.of(beforeModelCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeModelCallback(List beforeModelCallback) {\n if (beforeModelCallback == null) {\n this.beforeModelCallback = null;\n } else if (beforeModelCallback.isEmpty()) {\n this.beforeModelCallback = ImmutableList.of();\n } else {\n ImmutableList.Builder builder = ImmutableList.builder();\n for (BeforeModelCallbackBase callback : beforeModelCallback) {\n if (callback instanceof BeforeModelCallback beforeModelCallbackInstance) {\n builder.add(beforeModelCallbackInstance);\n } else if (callback instanceof BeforeModelCallbackSync beforeModelCallbackSyncInstance) {\n builder.add(\n (BeforeModelCallback)\n (callbackContext, llmRequest) ->\n Maybe.fromOptional(\n beforeModelCallbackSyncInstance.call(callbackContext, llmRequest)));\n } else {\n logger.warn(\n \"Invalid beforeModelCallback callback type: %s. Ignoring this callback.\",\n callback.getClass().getName());\n }\n }\n this.beforeModelCallback = builder.build();\n }\n\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeModelCallbackSync(BeforeModelCallbackSync beforeModelCallbackSync) {\n this.beforeModelCallback =\n ImmutableList.of(\n (callbackContext, llmRequest) ->\n Maybe.fromOptional(beforeModelCallbackSync.call(callbackContext, llmRequest)));\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterModelCallback(AfterModelCallback afterModelCallback) {\n this.afterModelCallback = ImmutableList.of(afterModelCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterModelCallback(List afterModelCallback) {\n if (afterModelCallback == null) {\n this.afterModelCallback = null;\n } else if (afterModelCallback.isEmpty()) {\n this.afterModelCallback = ImmutableList.of();\n } else {\n ImmutableList.Builder builder = ImmutableList.builder();\n for (AfterModelCallbackBase callback : afterModelCallback) {\n if (callback instanceof AfterModelCallback afterModelCallbackInstance) {\n builder.add(afterModelCallbackInstance);\n } else if (callback instanceof AfterModelCallbackSync afterModelCallbackSyncInstance) {\n builder.add(\n (AfterModelCallback)\n (callbackContext, llmResponse) ->\n Maybe.fromOptional(\n afterModelCallbackSyncInstance.call(callbackContext, llmResponse)));\n } else {\n logger.warn(\n \"Invalid afterModelCallback callback type: %s. Ignoring this callback.\",\n callback.getClass().getName());\n }\n }\n this.afterModelCallback = builder.build();\n }\n\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterModelCallbackSync(AfterModelCallbackSync afterModelCallbackSync) {\n this.afterModelCallback =\n ImmutableList.of(\n (callbackContext, llmResponse) ->\n Maybe.fromOptional(afterModelCallbackSync.call(callbackContext, llmResponse)));\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeAgentCallback(BeforeAgentCallback beforeAgentCallback) {\n this.beforeAgentCallback = ImmutableList.of(beforeAgentCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeAgentCallback(List beforeAgentCallback) {\n this.beforeAgentCallback = CallbackUtil.getBeforeAgentCallbacks(beforeAgentCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeAgentCallbackSync(BeforeAgentCallbackSync beforeAgentCallbackSync) {\n this.beforeAgentCallback =\n ImmutableList.of(\n (callbackContext) ->\n Maybe.fromOptional(beforeAgentCallbackSync.call(callbackContext)));\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterAgentCallback(AfterAgentCallback afterAgentCallback) {\n this.afterAgentCallback = ImmutableList.of(afterAgentCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterAgentCallback(List afterAgentCallback) {\n this.afterAgentCallback = CallbackUtil.getAfterAgentCallbacks(afterAgentCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterAgentCallbackSync(AfterAgentCallbackSync afterAgentCallbackSync) {\n this.afterAgentCallback =\n ImmutableList.of(\n (callbackContext) ->\n Maybe.fromOptional(afterAgentCallbackSync.call(callbackContext)));\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeToolCallback(BeforeToolCallback beforeToolCallback) {\n this.beforeToolCallback = ImmutableList.of(beforeToolCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeToolCallback(@Nullable List beforeToolCallbacks) {\n if (beforeToolCallbacks == null) {\n this.beforeToolCallback = null;\n } else if (beforeToolCallbacks.isEmpty()) {\n this.beforeToolCallback = ImmutableList.of();\n } else {\n ImmutableList.Builder builder = ImmutableList.builder();\n for (BeforeToolCallbackBase callback : beforeToolCallbacks) {\n if (callback instanceof BeforeToolCallback beforeToolCallbackInstance) {\n builder.add(beforeToolCallbackInstance);\n } else if (callback instanceof BeforeToolCallbackSync beforeToolCallbackSyncInstance) {\n builder.add(\n (invocationContext, baseTool, input, toolContext) ->\n Maybe.fromOptional(\n beforeToolCallbackSyncInstance.call(\n invocationContext, baseTool, input, toolContext)));\n } else {\n logger.warn(\n \"Invalid beforeToolCallback callback type: {}. Ignoring this callback.\",\n callback.getClass().getName());\n }\n }\n this.beforeToolCallback = builder.build();\n }\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeToolCallbackSync(BeforeToolCallbackSync beforeToolCallbackSync) {\n this.beforeToolCallback =\n ImmutableList.of(\n (invocationContext, baseTool, input, toolContext) ->\n Maybe.fromOptional(\n beforeToolCallbackSync.call(\n invocationContext, baseTool, input, toolContext)));\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterToolCallback(AfterToolCallback afterToolCallback) {\n this.afterToolCallback = ImmutableList.of(afterToolCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterToolCallback(@Nullable List afterToolCallbacks) {\n if (afterToolCallbacks == null) {\n this.afterToolCallback = null;\n } else if (afterToolCallbacks.isEmpty()) {\n this.afterToolCallback = ImmutableList.of();\n } else {\n ImmutableList.Builder builder = ImmutableList.builder();\n for (AfterToolCallbackBase callback : afterToolCallbacks) {\n if (callback instanceof AfterToolCallback afterToolCallbackInstance) {\n builder.add(afterToolCallbackInstance);\n } else if (callback instanceof AfterToolCallbackSync afterToolCallbackSyncInstance) {\n builder.add(\n (invocationContext, baseTool, input, toolContext, response) ->\n Maybe.fromOptional(\n afterToolCallbackSyncInstance.call(\n invocationContext, baseTool, input, toolContext, response)));\n } else {\n logger.warn(\n \"Invalid afterToolCallback callback type: {}. Ignoring this callback.\",\n callback.getClass().getName());\n }\n }\n this.afterToolCallback = builder.build();\n }\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterToolCallbackSync(AfterToolCallbackSync afterToolCallbackSync) {\n this.afterToolCallback =\n ImmutableList.of(\n (invocationContext, baseTool, input, toolContext, response) ->\n Maybe.fromOptional(\n afterToolCallbackSync.call(\n invocationContext, baseTool, input, toolContext, response)));\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder inputSchema(Schema inputSchema) {\n this.inputSchema = inputSchema;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder outputSchema(Schema outputSchema) {\n this.outputSchema = outputSchema;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder executor(Executor executor) {\n this.executor = executor;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder outputKey(String outputKey) {\n this.outputKey = outputKey;\n return this;\n }\n\n protected void validate() {\n this.disallowTransferToParent =\n this.disallowTransferToParent != null && this.disallowTransferToParent;\n this.disallowTransferToPeers =\n this.disallowTransferToPeers != null && this.disallowTransferToPeers;\n\n if (this.outputSchema != null) {\n if (!this.disallowTransferToParent || !this.disallowTransferToPeers) {\n System.err.println(\n \"Warning: Invalid config for agent \"\n + this.name\n + \": outputSchema cannot co-exist with agent transfer\"\n + \" configurations. Setting disallowTransferToParent=true and\"\n + \" disallowTransferToPeers=true.\");\n this.disallowTransferToParent = true;\n this.disallowTransferToPeers = true;\n }\n\n if (this.subAgents != null && !this.subAgents.isEmpty()) {\n throw new IllegalArgumentException(\n \"Invalid config for agent \"\n + this.name\n + \": if outputSchema is set, subAgents must be empty to disable agent\"\n + \" transfer.\");\n }\n if (this.toolsUnion != null && !this.toolsUnion.isEmpty()) {\n throw new IllegalArgumentException(\n \"Invalid config for agent \"\n + this.name\n + \": if outputSchema is set, tools must be empty.\");\n }\n }\n }\n\n public LlmAgent build() {\n validate();\n return new LlmAgent(this);\n }\n }\n\n protected BaseLlmFlow determineLlmFlow() {\n if (disallowTransferToParent() && disallowTransferToPeers() && subAgents().isEmpty()) {\n return new SingleFlow(maxSteps);\n } else {\n return new AutoFlow(maxSteps);\n }\n }\n\n private void maybeSaveOutputToState(Event event) {\n if (outputKey().isPresent() && event.finalResponse() && event.content().isPresent()) {\n // Concatenate text from all parts.\n Object output;\n String rawResult =\n event.content().flatMap(Content::parts).orElse(ImmutableList.of()).stream()\n .map(part -> part.text().orElse(\"\"))\n .collect(joining());\n\n Optional outputSchema = outputSchema();\n if (outputSchema.isPresent()) {\n try {\n Map validatedMap =\n SchemaUtils.validateOutputSchema(rawResult, outputSchema.get());\n output = validatedMap;\n } catch (JsonProcessingException e) {\n System.err.println(\n \"Error: LlmAgent output for outputKey '\"\n + outputKey().get()\n + \"' was not valid JSON, despite an outputSchema being present.\"\n + \" Saving raw output to state. Error: \"\n + e.getMessage());\n output = rawResult;\n } catch (IllegalArgumentException e) {\n System.err.println(\n \"Error: LlmAgent output for outputKey '\"\n + outputKey().get()\n + \"' did not match the outputSchema.\"\n + \" Saving raw output to state. Error: \"\n + e.getMessage());\n output = rawResult;\n }\n } else {\n output = rawResult;\n }\n event.actions().stateDelta().put(outputKey().get(), output);\n }\n }\n\n @Override\n protected Flowable runAsyncImpl(InvocationContext invocationContext) {\n return llmFlow.run(invocationContext).doOnNext(this::maybeSaveOutputToState);\n }\n\n @Override\n protected Flowable runLiveImpl(InvocationContext invocationContext) {\n return llmFlow.runLive(invocationContext).doOnNext(this::maybeSaveOutputToState);\n }\n\n /**\n * Constructs the text instruction for this agent based on the {@link #instruction} field.\n *\n *

This method is only for use by Agent Development Kit.\n *\n * @param context The context to retrieve the session state.\n * @return The resolved instruction as a {@link Single} wrapped string.\n */\n public Single canonicalInstruction(ReadonlyContext context) {\n if (instruction instanceof Instruction.Static staticInstr) {\n return Single.just(staticInstr.instruction());\n } else if (instruction instanceof Instruction.Provider provider) {\n return provider.getInstruction().apply(context);\n }\n throw new IllegalStateException(\"Unknown Instruction subtype: \" + instruction.getClass());\n }\n\n /**\n * Constructs the text global instruction for this agent based on the {@link #globalInstruction}\n * field.\n *\n *

This method is only for use by Agent Development Kit.\n *\n * @param context The context to retrieve the session state.\n * @return The resolved global instruction as a {@link Single} wrapped string.\n */\n public Single canonicalGlobalInstruction(ReadonlyContext context) {\n if (globalInstruction instanceof Instruction.Static staticInstr) {\n return Single.just(staticInstr.instruction());\n } else if (globalInstruction instanceof Instruction.Provider provider) {\n return provider.getInstruction().apply(context);\n }\n throw new IllegalStateException(\"Unknown Instruction subtype: \" + instruction.getClass());\n }\n\n /**\n * Constructs the list of tools for this agent based on the {@link #tools} field.\n *\n *

This method is only for use by Agent Development Kit.\n *\n * @param context The context to retrieve the session state.\n * @return The resolved list of tools as a {@link Single} wrapped list of {@link BaseTool}.\n */\n public Flowable canonicalTools(Optional context) {\n List> toolFlowables = new ArrayList<>();\n for (Object toolOrToolset : toolsUnion) {\n if (toolOrToolset instanceof BaseTool baseTool) {\n toolFlowables.add(Flowable.just(baseTool));\n } else if (toolOrToolset instanceof BaseToolset baseToolset) {\n toolFlowables.add(baseToolset.getTools(context.orElse(null)));\n } else {\n throw new IllegalArgumentException(\n \"Object in tools list is not of a supported type: \"\n + toolOrToolset.getClass().getName());\n }\n }\n return Flowable.concat(toolFlowables);\n }\n\n /** Overload of canonicalTools that defaults to an empty context. */\n public Flowable canonicalTools() {\n return canonicalTools(Optional.empty());\n }\n\n /** Convenience overload of canonicalTools that accepts a non-optional ReadonlyContext. */\n public Flowable canonicalTools(ReadonlyContext context) {\n return canonicalTools(Optional.ofNullable(context));\n }\n\n public Instruction instruction() {\n return instruction;\n }\n\n public Instruction globalInstruction() {\n return globalInstruction;\n }\n\n public Optional model() {\n return model;\n }\n\n public boolean planning() {\n return planning;\n }\n\n public Optional maxSteps() {\n return maxSteps;\n }\n\n public Optional generateContentConfig() {\n return generateContentConfig;\n }\n\n public Optional exampleProvider() {\n return exampleProvider;\n }\n\n public IncludeContents includeContents() {\n return includeContents;\n }\n\n public List tools() {\n return canonicalTools().toList().blockingGet();\n }\n\n public List toolsUnion() {\n return toolsUnion;\n }\n\n public boolean disallowTransferToParent() {\n return disallowTransferToParent;\n }\n\n public boolean disallowTransferToPeers() {\n return disallowTransferToPeers;\n }\n\n public Optional> beforeModelCallback() {\n return beforeModelCallback;\n }\n\n public Optional> afterModelCallback() {\n return afterModelCallback;\n }\n\n public Optional> beforeToolCallback() {\n return beforeToolCallback;\n }\n\n public Optional> afterToolCallback() {\n return afterToolCallback;\n }\n\n public Optional inputSchema() {\n return inputSchema;\n }\n\n public Optional outputSchema() {\n return outputSchema;\n }\n\n public Optional executor() {\n return executor;\n }\n\n public Optional outputKey() {\n return outputKey;\n }\n\n public Model resolvedModel() {\n if (resolvedModel == null) {\n synchronized (this) {\n if (resolvedModel == null) {\n resolvedModel = resolveModelInternal();\n }\n }\n }\n return resolvedModel;\n }\n\n /**\n * Resolves the model for this agent, checking first if it is defined locally, then searching\n * through ancestors.\n *\n *

This method is only for use by Agent Development Kit.\n *\n * @return The resolved {@link Model} for this agent.\n * @throws IllegalStateException if no model is found for this agent or its ancestors.\n */\n private Model resolveModelInternal() {\n if (this.model.isPresent()) {\n if (this.model().isPresent()) {\n return this.model.get();\n }\n }\n BaseAgent current = this.parentAgent();\n while (current != null) {\n if (current instanceof LlmAgent) {\n return ((LlmAgent) current).resolvedModel();\n }\n current = current.parentAgent();\n }\n throw new IllegalStateException(\"No model found for agent \" + name() + \" or its ancestors.\");\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/LoadArtifactsTool.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// LoadArtifactsTool.java\npackage com.google.adk.tools;\n\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.google.adk.JsonBaseModel;\nimport com.google.adk.models.LlmRequest;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.FunctionDeclaration;\nimport com.google.genai.types.FunctionResponse;\nimport com.google.genai.types.Part;\nimport com.google.genai.types.Schema;\nimport io.reactivex.rxjava3.core.Completable;\nimport io.reactivex.rxjava3.core.Observable;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.Optional;\n\n/**\n * A tool that loads artifacts and adds them to the session.\n *\n *

This tool informs the model about available artifacts and provides their content when\n * requested by the model through a function call.\n */\npublic final class LoadArtifactsTool extends BaseTool {\n public LoadArtifactsTool() {\n super(\"load_artifacts\", \"Loads the artifacts and adds them to the session.\");\n }\n\n @Override\n public Optional declaration() {\n return Optional.of(\n FunctionDeclaration.builder()\n .name(this.name())\n .description(this.description())\n .parameters(\n Schema.builder()\n .type(\"OBJECT\")\n .properties(\n ImmutableMap.of(\n \"artifact_names\",\n Schema.builder()\n .type(\"ARRAY\")\n .items(Schema.builder().type(\"STRING\").build())\n .build()))\n .build())\n .build());\n }\n\n @Override\n public Single> runAsync(Map args, ToolContext toolContext) {\n @SuppressWarnings(\"unchecked\")\n List artifactNames =\n (List) args.getOrDefault(\"artifact_names\", ImmutableList.of());\n return Single.just(ImmutableMap.of(\"artifact_names\", artifactNames));\n }\n\n @Override\n public Completable processLlmRequest(\n LlmRequest.Builder llmRequestBuilder, ToolContext toolContext) {\n return super.processLlmRequest(llmRequestBuilder, toolContext)\n .andThen(appendArtifactsToLlmRequest(llmRequestBuilder, toolContext));\n }\n\n public Completable appendArtifactsToLlmRequest(\n LlmRequest.Builder llmRequestBuilder, ToolContext toolContext) {\n\n return toolContext\n .listArtifacts()\n .flatMapCompletable(\n artifactNamesList -> {\n if (artifactNamesList.isEmpty()) {\n return Completable.complete();\n }\n\n appendInitialInstructions(llmRequestBuilder, artifactNamesList);\n\n return processLoadArtifactsFunctionCall(llmRequestBuilder, toolContext);\n });\n }\n\n private void appendInitialInstructions(\n LlmRequest.Builder llmRequestBuilder, List artifactNamesList) {\n try {\n String instructions =\n String.format(\n \"You have a list of artifacts:\\n %s\\n\\nWhen the user asks questions about\"\n + \" any of the artifacts, you should call the `load_artifacts` function\"\n + \" to load the artifact. Do not generate any text other than the\"\n + \" function call.\",\n JsonBaseModel.getMapper().writeValueAsString(artifactNamesList));\n llmRequestBuilder.appendInstructions(ImmutableList.of(instructions));\n } catch (JsonProcessingException e) {\n throw new IllegalStateException(\"Failed to serialize artifact names to JSON\", e);\n }\n }\n\n private Completable processLoadArtifactsFunctionCall(\n LlmRequest.Builder llmRequestBuilder, ToolContext toolContext) {\n\n LlmRequest currentRequestState = llmRequestBuilder.build();\n List currentContents = currentRequestState.contents();\n\n if (currentContents.isEmpty()) {\n return Completable.complete();\n }\n\n return Iterables.getLast(currentContents)\n .parts()\n .filter(partsList -> !partsList.isEmpty())\n .flatMap(partsList -> partsList.get(0).functionResponse())\n .filter(fr -> Objects.equals(fr.name().orElse(null), \"load_artifacts\"))\n .flatMap(FunctionResponse::response)\n .flatMap(responseMap -> Optional.ofNullable(responseMap.get(\"artifact_names\")))\n .filter(obj -> obj instanceof List)\n .map(obj -> (List) obj)\n .filter(list -> !list.isEmpty())\n .map(\n artifactNamesRaw -> {\n @SuppressWarnings(\"unchecked\")\n List artifactNamesToLoad = (List) artifactNamesRaw;\n\n return Observable.fromIterable(artifactNamesToLoad)\n .flatMapCompletable(\n artifactName ->\n loadAndAppendIndividualArtifact(\n llmRequestBuilder, toolContext, artifactName));\n })\n .orElse(Completable.complete());\n }\n\n private Completable loadAndAppendIndividualArtifact(\n LlmRequest.Builder llmRequestBuilder, ToolContext toolContext, String artifactName) {\n\n return toolContext\n .loadArtifact(artifactName, Optional.empty())\n .flatMapCompletable(\n actualArtifact ->\n Completable.fromAction(\n () ->\n appendArtifactToLlmRequest(\n llmRequestBuilder,\n \"Artifact \" + artifactName + \" is:\",\n actualArtifact)));\n }\n\n private void appendArtifactToLlmRequest(\n LlmRequest.Builder llmRequestBuilder, String prefix, Part artifact) {\n llmRequestBuilder.contents(\n ImmutableList.builder()\n .addAll(llmRequestBuilder.build().contents())\n .add(Content.fromParts(Part.fromText(prefix), artifact))\n .build());\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/mcp/McpToolset.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools.mcp;\n\nimport static com.google.common.collect.ImmutableList.toImmutableList;\n\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.google.adk.JsonBaseModel;\nimport com.google.adk.agents.ReadonlyContext;\nimport com.google.adk.tools.BaseTool;\nimport com.google.adk.tools.BaseToolset;\nimport io.modelcontextprotocol.client.McpSyncClient;\nimport io.modelcontextprotocol.client.transport.ServerParameters;\nimport io.modelcontextprotocol.spec.McpSchema.ListToolsResult;\nimport io.reactivex.rxjava3.core.Flowable;\nimport java.util.Objects;\nimport java.util.Optional;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * Connects to a MCP Server, and retrieves MCP Tools into ADK Tools.\n *\n *

Attributes:\n *\n *

    \n *
  • {@code connectionParams}: The connection parameters to the MCP server. Can be either {@code\n * ServerParameters} or {@code SseServerParameters}.\n *
  • {@code session}: The MCP session being initialized with the connection.\n *
\n */\npublic class McpToolset implements BaseToolset {\n private static final Logger logger = LoggerFactory.getLogger(McpToolset.class);\n private final McpSessionManager mcpSessionManager;\n private McpSyncClient mcpSession;\n private final ObjectMapper objectMapper;\n private final Optional toolFilter;\n\n private static final int MAX_RETRIES = 3;\n private static final long RETRY_DELAY_MILLIS = 100;\n\n /**\n * Initializes the McpToolset with SSE server parameters.\n *\n * @param connectionParams The SSE connection parameters to the MCP server.\n * @param objectMapper An ObjectMapper instance for parsing schemas.\n * @param toolFilter An Optional containing either a ToolPredicate or a List of tool names.\n */\n public McpToolset(\n SseServerParameters connectionParams,\n ObjectMapper objectMapper,\n Optional toolFilter) {\n Objects.requireNonNull(connectionParams);\n Objects.requireNonNull(objectMapper);\n this.objectMapper = objectMapper;\n this.mcpSessionManager = new McpSessionManager(connectionParams);\n this.toolFilter = toolFilter;\n }\n\n /**\n * Initializes the McpToolset with SSE server parameters and no tool filter.\n *\n * @param connectionParams The SSE connection parameters to the MCP server.\n * @param objectMapper An ObjectMapper instance for parsing schemas.\n */\n public McpToolset(SseServerParameters connectionParams, ObjectMapper objectMapper) {\n this(connectionParams, objectMapper, Optional.empty());\n }\n\n /**\n * Initializes the McpToolset with local server parameters.\n *\n * @param connectionParams The local server connection parameters to the MCP server.\n * @param objectMapper An ObjectMapper instance for parsing schemas.\n * @param toolFilter An Optional containing either a ToolPredicate or a List of tool names.\n */\n public McpToolset(\n ServerParameters connectionParams, ObjectMapper objectMapper, Optional toolFilter) {\n Objects.requireNonNull(connectionParams);\n Objects.requireNonNull(objectMapper);\n this.objectMapper = objectMapper;\n this.mcpSessionManager = new McpSessionManager(connectionParams);\n this.toolFilter = toolFilter;\n }\n\n /**\n * Initializes the McpToolset with local server parameters and no tool filter.\n *\n * @param connectionParams The local server connection parameters to the MCP server.\n * @param objectMapper An ObjectMapper instance for parsing schemas.\n */\n public McpToolset(ServerParameters connectionParams, ObjectMapper objectMapper) {\n this(connectionParams, objectMapper, Optional.empty());\n }\n\n /**\n * Initializes the McpToolset with SSE server parameters, using the ObjectMapper used across the\n * ADK.\n *\n * @param connectionParams The SSE connection parameters to the MCP server.\n * @param toolFilter An Optional containing either a ToolPredicate or a List of tool names.\n */\n public McpToolset(SseServerParameters connectionParams, Optional toolFilter) {\n this(connectionParams, JsonBaseModel.getMapper(), toolFilter);\n }\n\n /**\n * Initializes the McpToolset with SSE server parameters, using the ObjectMapper used across the\n * ADK and no tool filter.\n *\n * @param connectionParams The SSE connection parameters to the MCP server.\n */\n public McpToolset(SseServerParameters connectionParams) {\n this(connectionParams, JsonBaseModel.getMapper(), Optional.empty());\n }\n\n /**\n * Initializes the McpToolset with local server parameters, using the ObjectMapper used across the\n * ADK.\n *\n * @param connectionParams The local server connection parameters to the MCP server.\n * @param toolFilter An Optional containing either a ToolPredicate or a List of tool names.\n */\n public McpToolset(ServerParameters connectionParams, Optional toolFilter) {\n this(connectionParams, JsonBaseModel.getMapper(), toolFilter);\n }\n\n /**\n * Initializes the McpToolset with local server parameters, using the ObjectMapper used across the\n * ADK and no tool filter.\n *\n * @param connectionParams The local server connection parameters to the MCP server.\n */\n public McpToolset(ServerParameters connectionParams) {\n this(connectionParams, JsonBaseModel.getMapper(), Optional.empty());\n }\n\n @Override\n public Flowable getTools(ReadonlyContext readonlyContext) {\n return Flowable.fromCallable(\n () -> {\n for (int i = 0; i < MAX_RETRIES; i++) {\n try {\n if (this.mcpSession == null) {\n logger.info(\"MCP session is null or closed, initializing (attempt {}).\", i + 1);\n this.mcpSession = this.mcpSessionManager.createSession();\n }\n\n ListToolsResult toolsResponse = this.mcpSession.listTools();\n return toolsResponse.tools().stream()\n .map(\n tool ->\n new McpTool(\n tool, this.mcpSession, this.mcpSessionManager, this.objectMapper))\n .filter(\n tool ->\n isToolSelected(\n tool, toolFilter, Optional.ofNullable(readonlyContext)))\n .collect(toImmutableList());\n } catch (IllegalArgumentException e) {\n // This could happen if parameters for tool loading are somehow invalid.\n // This is likely a fatal error and should not be retried.\n logger.error(\"Invalid argument encountered during tool loading.\", e);\n throw new McpToolLoadingException(\n \"Invalid argument encountered during tool loading.\", e);\n } catch (RuntimeException e) { // Catch any other unexpected runtime exceptions\n logger.error(\"Unexpected error during tool loading, retry attempt \" + (i + 1), e);\n if (i < MAX_RETRIES - 1) {\n // For other general exceptions, we might still want to retry if they are\n // potentially transient, or if we don't have more specific handling. But it's\n // better to be specific. For now, we'll treat them as potentially retryable but\n // log\n // them at a higher level.\n try {\n logger.info(\n \"Reinitializing MCP session before next retry for unexpected error.\");\n this.mcpSession = this.mcpSessionManager.createSession();\n Thread.sleep(RETRY_DELAY_MILLIS);\n } catch (InterruptedException ie) {\n Thread.currentThread().interrupt();\n logger.error(\n \"Interrupted during retry delay for loadTools (unexpected error).\", ie);\n throw new McpToolLoadingException(\n \"Interrupted during retry delay (unexpected error)\", ie);\n } catch (RuntimeException reinitE) {\n logger.error(\n \"Failed to reinitialize session during retry (unexpected error).\",\n reinitE);\n throw new McpInitializationException(\n \"Failed to reinitialize session during tool loading retry (unexpected\"\n + \" error).\",\n reinitE);\n }\n } else {\n logger.error(\n \"Failed to load tools after multiple retries due to unexpected error.\", e);\n throw new McpToolLoadingException(\n \"Failed to load tools after multiple retries due to unexpected error.\", e);\n }\n }\n }\n // This line should ideally not be reached if retries are handled correctly or an\n // exception is always thrown.\n throw new IllegalStateException(\"Unexpected state in getTools retry loop\");\n })\n .flatMapIterable(tools -> tools);\n }\n\n @Override\n public void close() {\n if (this.mcpSession != null) {\n try {\n this.mcpSession.close();\n logger.debug(\"MCP session closed successfully.\");\n } catch (RuntimeException e) {\n logger.error(\"Failed to close MCP session\", e);\n // We don't throw an exception here, as closing is a cleanup operation and\n // failing to close shouldn't prevent the program from continuing (or exiting).\n // However, we log the error for debugging purposes.\n } finally {\n this.mcpSession = null;\n }\n }\n }\n\n /** Base exception for all errors originating from {@code McpToolset}. */\n public static class McpToolsetException extends RuntimeException {\n public McpToolsetException(String message, Throwable cause) {\n super(message, cause);\n }\n }\n\n /** Exception thrown when there's an error during MCP session initialization. */\n public static class McpInitializationException extends McpToolsetException {\n public McpInitializationException(String message, Throwable cause) {\n super(message, cause);\n }\n }\n\n /** Exception thrown when there's an error during loading tools from the MCP server. */\n public static class McpToolLoadingException extends McpToolsetException {\n public McpToolLoadingException(String message, Throwable cause) {\n super(message, cause);\n }\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/sessions/State.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\nimport java.util.Collection;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.Objects;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentMap;\n\n/** A {@link State} object that also keeps track of the changes to the state. */\n@SuppressWarnings(\"ShouldNotSubclass\")\npublic final class State implements ConcurrentMap {\n\n public static final String APP_PREFIX = \"app:\";\n public static final String USER_PREFIX = \"user:\";\n public static final String TEMP_PREFIX = \"temp:\";\n\n // Sentinel object to mark removed entries in the delta map\n private static final Object REMOVED = new Object();\n\n private final ConcurrentMap state;\n private final ConcurrentMap delta;\n\n public State(ConcurrentMap state) {\n this(state, new ConcurrentHashMap<>());\n }\n\n public State(ConcurrentMap state, ConcurrentMap delta) {\n this.state = Objects.requireNonNull(state);\n this.delta = delta;\n }\n\n @Override\n public void clear() {\n state.clear();\n }\n\n @Override\n public boolean containsKey(Object key) {\n return state.containsKey(key);\n }\n\n @Override\n public boolean containsValue(Object value) {\n return state.containsValue(value);\n }\n\n @Override\n public Set> entrySet() {\n return state.entrySet();\n }\n\n @Override\n public boolean equals(Object o) {\n if (o == this) {\n return true;\n }\n if (!(o instanceof State other)) {\n return false;\n }\n return state.equals(other.state);\n }\n\n @Override\n public Object get(Object key) {\n return state.get(key);\n }\n\n @Override\n public int hashCode() {\n return state.hashCode();\n }\n\n @Override\n public boolean isEmpty() {\n return state.isEmpty();\n }\n\n @Override\n public Set keySet() {\n return state.keySet();\n }\n\n @Override\n public Object put(String key, Object value) {\n Object oldValue = state.put(key, value);\n delta.put(key, value);\n return oldValue;\n }\n\n @Override\n public Object putIfAbsent(String key, Object value) {\n Object existingValue = state.putIfAbsent(key, value);\n if (existingValue == null) {\n delta.put(key, value);\n }\n return existingValue;\n }\n\n @Override\n public void putAll(Map m) {\n state.putAll(m);\n delta.putAll(m);\n }\n\n @Override\n public Object remove(Object key) {\n if (state.containsKey(key)) {\n delta.put((String) key, REMOVED);\n }\n return state.remove(key);\n }\n\n @Override\n public boolean remove(Object key, Object value) {\n boolean removed = state.remove(key, value);\n if (removed) {\n delta.put((String) key, REMOVED);\n }\n return removed;\n }\n\n @Override\n public boolean replace(String key, Object oldValue, Object newValue) {\n boolean replaced = state.replace(key, oldValue, newValue);\n if (replaced) {\n delta.put(key, newValue);\n }\n return replaced;\n }\n\n @Override\n public Object replace(String key, Object value) {\n Object oldValue = state.replace(key, value);\n if (oldValue != null) {\n delta.put(key, value);\n }\n return oldValue;\n }\n\n @Override\n public int size() {\n return state.size();\n }\n\n @Override\n public Collection values() {\n return state.values();\n }\n\n public boolean hasDelta() {\n return !delta.isEmpty();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/events/EventActions.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.google.adk.events;\n\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.databind.annotation.JsonDeserialize;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport com.google.genai.types.Part;\nimport java.util.Objects;\nimport java.util.Optional;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentMap;\nimport javax.annotation.Nullable;\n\n/** Represents the actions attached to an event. */\n// TODO - b/414081262 make json wire camelCase\n@JsonDeserialize(builder = EventActions.Builder.class)\npublic class EventActions {\n\n private Optional skipSummarization = Optional.empty();\n private ConcurrentMap stateDelta = new ConcurrentHashMap<>();\n private ConcurrentMap artifactDelta = new ConcurrentHashMap<>();\n private Optional transferToAgent = Optional.empty();\n private Optional escalate = Optional.empty();\n private ConcurrentMap> requestedAuthConfigs =\n new ConcurrentHashMap<>();\n private Optional endInvocation = Optional.empty();\n\n /** Default constructor for Jackson. */\n public EventActions() {}\n\n @JsonProperty(\"skipSummarization\")\n public Optional skipSummarization() {\n return skipSummarization;\n }\n\n public void setSkipSummarization(@Nullable Boolean skipSummarization) {\n this.skipSummarization = Optional.ofNullable(skipSummarization);\n }\n\n public void setSkipSummarization(Optional skipSummarization) {\n this.skipSummarization = skipSummarization;\n }\n\n public void setSkipSummarization(boolean skipSummarization) {\n this.skipSummarization = Optional.of(skipSummarization);\n }\n\n @JsonProperty(\"stateDelta\")\n public ConcurrentMap stateDelta() {\n return stateDelta;\n }\n\n public void setStateDelta(ConcurrentMap stateDelta) {\n this.stateDelta = stateDelta;\n }\n\n @JsonProperty(\"artifactDelta\")\n public ConcurrentMap artifactDelta() {\n return artifactDelta;\n }\n\n public void setArtifactDelta(ConcurrentMap artifactDelta) {\n this.artifactDelta = artifactDelta;\n }\n\n @JsonProperty(\"transferToAgent\")\n public Optional transferToAgent() {\n return transferToAgent;\n }\n\n public void setTransferToAgent(Optional transferToAgent) {\n this.transferToAgent = transferToAgent;\n }\n\n public void setTransferToAgent(String transferToAgent) {\n this.transferToAgent = Optional.ofNullable(transferToAgent);\n }\n\n @JsonProperty(\"escalate\")\n public Optional escalate() {\n return escalate;\n }\n\n public void setEscalate(Optional escalate) {\n this.escalate = escalate;\n }\n\n public void setEscalate(boolean escalate) {\n this.escalate = Optional.of(escalate);\n }\n\n @JsonProperty(\"requestedAuthConfigs\")\n public ConcurrentMap> requestedAuthConfigs() {\n return requestedAuthConfigs;\n }\n\n public void setRequestedAuthConfigs(\n ConcurrentMap> requestedAuthConfigs) {\n this.requestedAuthConfigs = requestedAuthConfigs;\n }\n\n @JsonProperty(\"endInvocation\")\n public Optional endInvocation() {\n return endInvocation;\n }\n\n public void setEndInvocation(Optional endInvocation) {\n this.endInvocation = endInvocation;\n }\n\n public void setEndInvocation(boolean endInvocation) {\n this.endInvocation = Optional.of(endInvocation);\n }\n\n public static Builder builder() {\n return new Builder();\n }\n\n public Builder toBuilder() {\n return new Builder(this);\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (!(o instanceof EventActions that)) {\n return false;\n }\n return Objects.equals(skipSummarization, that.skipSummarization)\n && Objects.equals(stateDelta, that.stateDelta)\n && Objects.equals(artifactDelta, that.artifactDelta)\n && Objects.equals(transferToAgent, that.transferToAgent)\n && Objects.equals(escalate, that.escalate)\n && Objects.equals(requestedAuthConfigs, that.requestedAuthConfigs)\n && Objects.equals(endInvocation, that.endInvocation);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(\n skipSummarization,\n stateDelta,\n artifactDelta,\n transferToAgent,\n escalate,\n requestedAuthConfigs,\n endInvocation);\n }\n\n /** Builder for {@link EventActions}. */\n public static class Builder {\n private Optional skipSummarization = Optional.empty();\n private ConcurrentMap stateDelta = new ConcurrentHashMap<>();\n private ConcurrentMap artifactDelta = new ConcurrentHashMap<>();\n private Optional transferToAgent = Optional.empty();\n private Optional escalate = Optional.empty();\n private ConcurrentMap> requestedAuthConfigs =\n new ConcurrentHashMap<>();\n private Optional endInvocation = Optional.empty();\n\n public Builder() {}\n\n private Builder(EventActions eventActions) {\n this.skipSummarization = eventActions.skipSummarization();\n this.stateDelta = new ConcurrentHashMap<>(eventActions.stateDelta());\n this.artifactDelta = new ConcurrentHashMap<>(eventActions.artifactDelta());\n this.transferToAgent = eventActions.transferToAgent();\n this.escalate = eventActions.escalate();\n this.requestedAuthConfigs = new ConcurrentHashMap<>(eventActions.requestedAuthConfigs());\n this.endInvocation = eventActions.endInvocation();\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"skipSummarization\")\n public Builder skipSummarization(boolean skipSummarization) {\n this.skipSummarization = Optional.of(skipSummarization);\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"stateDelta\")\n public Builder stateDelta(ConcurrentMap value) {\n this.stateDelta = value;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"artifactDelta\")\n public Builder artifactDelta(ConcurrentMap value) {\n this.artifactDelta = value;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"transferToAgent\")\n public Builder transferToAgent(String agentId) {\n this.transferToAgent = Optional.ofNullable(agentId);\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"escalate\")\n public Builder escalate(boolean escalate) {\n this.escalate = Optional.of(escalate);\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"requestedAuthConfigs\")\n public Builder requestedAuthConfigs(\n ConcurrentMap> value) {\n this.requestedAuthConfigs = value;\n return this;\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"endInvocation\")\n public Builder endInvocation(boolean endInvocation) {\n this.endInvocation = Optional.of(endInvocation);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder merge(EventActions other) {\n if (other.skipSummarization().isPresent()) {\n this.skipSummarization = other.skipSummarization();\n }\n if (other.stateDelta() != null) {\n this.stateDelta.putAll(other.stateDelta());\n }\n if (other.artifactDelta() != null) {\n this.artifactDelta.putAll(other.artifactDelta());\n }\n if (other.transferToAgent().isPresent()) {\n this.transferToAgent = other.transferToAgent();\n }\n if (other.escalate().isPresent()) {\n this.escalate = other.escalate();\n }\n if (other.requestedAuthConfigs() != null) {\n this.requestedAuthConfigs.putAll(other.requestedAuthConfigs());\n }\n if (other.endInvocation().isPresent()) {\n this.endInvocation = other.endInvocation();\n }\n return this;\n }\n\n public EventActions build() {\n EventActions eventActions = new EventActions();\n eventActions.setSkipSummarization(this.skipSummarization);\n eventActions.setStateDelta(this.stateDelta);\n eventActions.setArtifactDelta(this.artifactDelta);\n eventActions.setTransferToAgent(this.transferToAgent);\n eventActions.setEscalate(this.escalate);\n eventActions.setRequestedAuthConfigs(this.requestedAuthConfigs);\n eventActions.setEndInvocation(this.endInvocation);\n return eventActions;\n }\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/Telemetry.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk;\n\nimport static com.google.common.collect.ImmutableList.toImmutableList;\n\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.events.Event;\nimport com.google.adk.models.LlmRequest;\nimport com.google.adk.models.LlmResponse;\nimport com.google.common.collect.ImmutableList;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.Part;\nimport io.opentelemetry.api.GlobalOpenTelemetry;\nimport io.opentelemetry.api.trace.Span;\nimport io.opentelemetry.api.trace.Tracer;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * Utility class for capturing and reporting telemetry data within the ADK. This class provides\n * methods to trace various aspects of the agent's execution, including tool calls, tool responses,\n * LLM interactions, and data handling. It leverages OpenTelemetry for tracing and logging for\n * detailed information. These traces can then be exported through the ADK Dev Server UI.\n */\npublic class Telemetry {\n\n private static final Logger log = LoggerFactory.getLogger(Telemetry.class);\n private static final Tracer tracer = GlobalOpenTelemetry.getTracer(\"gcp.vertex.agent\");\n\n private Telemetry() {}\n\n /**\n * Traces tool call arguments.\n *\n * @param args The arguments to the tool call.\n */\n public static void traceToolCall(Map args) {\n Span span = Span.current();\n if (span == null || !span.getSpanContext().isValid()) {\n log.trace(\"traceToolCall: No valid span in current context.\");\n return;\n }\n\n span.setAttribute(\"gen_ai.system\", \"gcp.vertex.agent\");\n try {\n span.setAttribute(\n \"gcp.vertex.agent.tool_call_args\", JsonBaseModel.getMapper().writeValueAsString(args));\n } catch (JsonProcessingException e) {\n log.warn(\"traceToolCall: Failed to serialize tool call args to JSON\", e);\n }\n }\n\n /**\n * Traces tool response event.\n *\n * @param invocationContext The invocation context for the current agent run.\n * @param eventId The ID of the event.\n * @param functionResponseEvent The function response event.\n */\n public static void traceToolResponse(\n InvocationContext invocationContext, String eventId, Event functionResponseEvent) {\n Span span = Span.current();\n if (span == null || !span.getSpanContext().isValid()) {\n log.trace(\"traceToolResponse: No valid span in current context.\");\n return;\n }\n\n span.setAttribute(\"gen_ai.system\", \"gcp.vertex.agent\");\n span.setAttribute(\"gcp.vertex.agent.invocation_id\", invocationContext.invocationId());\n span.setAttribute(\"gcp.vertex.agent.event_id\", eventId);\n span.setAttribute(\"gcp.vertex.agent.tool_response\", functionResponseEvent.toJson());\n\n // Setting empty llm request and response (as the AdkDevServer UI expects these)\n span.setAttribute(\"gcp.vertex.agent.llm_request\", \"{}\");\n span.setAttribute(\"gcp.vertex.agent.llm_response\", \"{}\");\n if (invocationContext.session() != null && invocationContext.session().id() != null) {\n span.setAttribute(\"gcp.vertex.agent.session_id\", invocationContext.session().id());\n }\n }\n\n /**\n * Builds a dictionary representation of the LLM request for tracing. {@code GenerationConfig} is\n * included as a whole. For other fields like {@code Content}, parts that cannot be easily\n * serialized or are not needed for the trace (e.g., inlineData) are excluded.\n *\n * @param llmRequest The LlmRequest object.\n * @return A Map representation of the LLM request for tracing.\n */\n private static Map buildLlmRequestForTrace(LlmRequest llmRequest) {\n Map result = new HashMap<>();\n result.put(\"model\", llmRequest.model().orElse(null));\n llmRequest.config().ifPresent(config -> result.put(\"config\", config));\n\n List contentsList = new ArrayList<>();\n for (Content content : llmRequest.contents()) {\n ImmutableList filteredParts =\n content.parts().orElse(ImmutableList.of()).stream()\n .filter(part -> part.inlineData().isEmpty())\n .collect(toImmutableList());\n\n Content.Builder contentBuilder = Content.builder();\n content.role().ifPresent(contentBuilder::role);\n contentBuilder.parts(filteredParts);\n contentsList.add(contentBuilder.build());\n }\n result.put(\"contents\", contentsList);\n return result;\n }\n\n /**\n * Traces a call to the LLM.\n *\n * @param invocationContext The invocation context.\n * @param eventId The ID of the event associated with this LLM call/response.\n * @param llmRequest The LLM request object.\n * @param llmResponse The LLM response object.\n */\n public static void traceCallLlm(\n InvocationContext invocationContext,\n String eventId,\n LlmRequest llmRequest,\n LlmResponse llmResponse) {\n Span span = Span.current();\n if (span == null || !span.getSpanContext().isValid()) {\n log.trace(\"traceCallLlm: No valid span in current context.\");\n return;\n }\n\n span.setAttribute(\"gen_ai.system\", \"gcp.vertex.agent\");\n llmRequest.model().ifPresent(modelName -> span.setAttribute(\"gen_ai.request.model\", modelName));\n span.setAttribute(\"gcp.vertex.agent.invocation_id\", invocationContext.invocationId());\n span.setAttribute(\"gcp.vertex.agent.event_id\", eventId);\n\n if (invocationContext.session() != null && invocationContext.session().id() != null) {\n span.setAttribute(\"gcp.vertex.agent.session_id\", invocationContext.session().id());\n } else {\n log.trace(\n \"traceCallLlm: InvocationContext session or session ID is null, cannot set\"\n + \" gcp.vertex.agent.session_id\");\n }\n\n try {\n span.setAttribute(\n \"gcp.vertex.agent.llm_request\",\n JsonBaseModel.getMapper().writeValueAsString(buildLlmRequestForTrace(llmRequest)));\n span.setAttribute(\"gcp.vertex.agent.llm_response\", llmResponse.toJson());\n } catch (JsonProcessingException e) {\n log.warn(\"traceCallLlm: Failed to serialize LlmRequest or LlmResponse to JSON\", e);\n }\n }\n\n /**\n * Traces the sending of data (history or new content) to the agent/model.\n *\n * @param invocationContext The invocation context.\n * @param eventId The ID of the event, if applicable.\n * @param data A list of content objects being sent.\n */\n public static void traceSendData(\n InvocationContext invocationContext, String eventId, List data) {\n Span span = Span.current();\n if (span == null || !span.getSpanContext().isValid()) {\n log.trace(\"traceSendData: No valid span in current context.\");\n return;\n }\n\n span.setAttribute(\"gcp.vertex.agent.invocation_id\", invocationContext.invocationId());\n if (eventId != null && !eventId.isEmpty()) {\n span.setAttribute(\"gcp.vertex.agent.event_id\", eventId);\n }\n\n if (invocationContext.session() != null && invocationContext.session().id() != null) {\n span.setAttribute(\"gcp.vertex.agent.session_id\", invocationContext.session().id());\n }\n\n try {\n List> dataList = new ArrayList<>();\n if (data != null) {\n for (Content content : data) {\n if (content != null) {\n dataList.add(\n JsonBaseModel.getMapper()\n .convertValue(content, new TypeReference>() {}));\n }\n }\n }\n span.setAttribute(\"gcp.vertex.agent.data\", JsonBaseModel.toJsonString(dataList));\n } catch (IllegalStateException e) {\n log.warn(\"traceSendData: Failed to serialize data to JSON\", e);\n }\n }\n\n /**\n * Gets the tracer.\n *\n * @return The tracer.\n */\n public static Tracer getTracer() {\n return tracer;\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/applicationintegrationtoolset/IntegrationClient.java", "package com.google.adk.tools.applicationintegrationtoolset;\n\nimport static com.google.common.base.Strings.isNullOrEmpty;\n\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.fasterxml.jackson.databind.node.ObjectNode;\nimport com.google.adk.tools.applicationintegrationtoolset.IntegrationConnectorTool.HttpExecutor;\nimport com.google.common.base.Preconditions;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport java.io.IOException;\nimport java.net.URI;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.util.Arrays;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.Map;\nimport java.util.Objects;\n\n/**\n * Utility class for interacting with Google Cloud Application Integration.\n *\n *

This class provides methods for retrieving OpenAPI spec for an integration or a connection.\n */\npublic class IntegrationClient {\n String project;\n String location;\n String integration;\n List triggers;\n String connection;\n Map> entityOperations;\n List actions;\n private final HttpExecutor httpExecutor;\n public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();\n\n IntegrationClient(\n String project,\n String location,\n String integration,\n List triggers,\n String connection,\n Map> entityOperations,\n List actions,\n HttpExecutor httpExecutor) {\n this.project = project;\n this.location = location;\n this.integration = integration;\n this.triggers = triggers;\n this.connection = connection;\n this.entityOperations = entityOperations;\n this.actions = actions;\n this.httpExecutor = httpExecutor;\n if (!isNullOrEmpty(connection)) {\n validate();\n }\n }\n\n private void validate() {\n // Check if both are null, throw exception\n\n if (this.entityOperations == null && this.actions == null) {\n throw new IllegalArgumentException(\n \"No entity operations or actions provided. Please provide at least one of them.\");\n }\n\n if (this.entityOperations != null) {\n Preconditions.checkArgument(\n !this.entityOperations.isEmpty(), \"entityOperations map cannot be empty\");\n for (Map.Entry> entry : this.entityOperations.entrySet()) {\n String key = entry.getKey();\n List value = entry.getValue();\n Preconditions.checkArgument(\n key != null && !key.isEmpty(),\n \"Enitity in entityOperations map cannot be null or empty\");\n Preconditions.checkArgument(\n value != null, \"Operations for entity '%s' cannot be null\", key);\n for (String str : value) {\n Preconditions.checkArgument(\n str != null && !str.isEmpty(),\n \"Operation for entity '%s' cannot be null or empty\",\n key);\n }\n }\n }\n\n // Validate actions if it's not null\n if (this.actions != null) {\n Preconditions.checkArgument(!this.actions.isEmpty(), \"Actions list cannot be empty\");\n Preconditions.checkArgument(\n this.actions.stream().allMatch(Objects::nonNull),\n \"Actions list cannot contain null values\");\n Preconditions.checkArgument(\n this.actions.stream().noneMatch(String::isEmpty),\n \"Actions list cannot contain empty strings\");\n }\n }\n\n String generateOpenApiSpec() throws Exception {\n String url =\n String.format(\n \"https://%s-integrations.googleapis.com/v1/projects/%s/locations/%s:generateOpenApiSpec\",\n this.location, this.project, this.location);\n\n String jsonRequestBody =\n OBJECT_MAPPER.writeValueAsString(\n ImmutableMap.of(\n \"apiTriggerResources\",\n ImmutableList.of(\n ImmutableMap.of(\n \"integrationResource\",\n this.integration,\n \"triggerId\",\n Arrays.asList(this.triggers))),\n \"fileFormat\",\n \"JSON\"));\n HttpRequest request =\n HttpRequest.newBuilder()\n .uri(URI.create(url))\n .header(\"Authorization\", \"Bearer \" + httpExecutor.getToken())\n .header(\"Content-Type\", \"application/json\")\n .POST(HttpRequest.BodyPublishers.ofString(jsonRequestBody))\n .build();\n HttpResponse response =\n httpExecutor.send(request, HttpResponse.BodyHandlers.ofString());\n\n if (response.statusCode() < 200 || response.statusCode() >= 300) {\n throw new Exception(\"Error fetching OpenAPI spec. Status: \" + response.statusCode());\n }\n return response.body();\n }\n\n @SuppressWarnings(\"unchecked\")\n ObjectNode getOpenApiSpecForConnection(String toolName, String toolInstructions)\n throws IOException, InterruptedException {\n final String integrationName = \"ExecuteConnection\";\n\n ConnectionsClient connectionsClient = createConnectionsClient();\n\n ImmutableMap baseSpecMap = ConnectionsClient.getConnectorBaseSpec();\n ObjectNode connectorSpec = OBJECT_MAPPER.valueToTree(baseSpecMap);\n\n ObjectNode paths = (ObjectNode) connectorSpec.path(\"paths\");\n ObjectNode schemas = (ObjectNode) connectorSpec.path(\"components\").path(\"schemas\");\n\n if (this.entityOperations != null) {\n for (Map.Entry> entry : this.entityOperations.entrySet()) {\n String entity = entry.getKey();\n List operations = entry.getValue();\n\n ConnectionsClient.EntitySchemaAndOperations schemaInfo;\n try {\n schemaInfo = connectionsClient.getEntitySchemaAndOperations(entity);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n throw new IOException(\"Operation was interrupted while getting entity schema\", e);\n }\n\n Map schemaMap = schemaInfo.schema;\n List supportedOperations = schemaInfo.operations;\n\n if (operations == null || operations.isEmpty()) {\n operations = supportedOperations;\n }\n\n String jsonSchemaAsString = OBJECT_MAPPER.writeValueAsString(schemaMap);\n String entityLower = entity.toLowerCase(Locale.ROOT);\n\n schemas.set(\n \"connectorInputPayload_\" + entityLower,\n OBJECT_MAPPER.valueToTree(connectionsClient.connectorPayload(schemaMap)));\n\n for (String operation : operations) {\n String operationLower = operation.toLowerCase(Locale.ROOT);\n String path =\n String.format(\n \"/v2/projects/%s/locations/%s/integrations/%s:execute?triggerId=api_trigger/%s#%s_%s\",\n this.project,\n this.location,\n integrationName,\n integrationName,\n operationLower,\n entityLower);\n\n switch (operationLower) {\n case \"create\":\n paths.set(\n path,\n OBJECT_MAPPER.valueToTree(\n ConnectionsClient.createOperation(entityLower, toolName, toolInstructions)));\n schemas.set(\n \"create_\" + entityLower + \"_Request\",\n OBJECT_MAPPER.valueToTree(ConnectionsClient.createOperationRequest(entityLower)));\n break;\n case \"update\":\n paths.set(\n path,\n OBJECT_MAPPER.valueToTree(\n ConnectionsClient.updateOperation(entityLower, toolName, toolInstructions)));\n schemas.set(\n \"update_\" + entityLower + \"_Request\",\n OBJECT_MAPPER.valueToTree(ConnectionsClient.updateOperationRequest(entityLower)));\n break;\n case \"delete\":\n paths.set(\n path,\n OBJECT_MAPPER.valueToTree(\n ConnectionsClient.deleteOperation(entityLower, toolName, toolInstructions)));\n schemas.set(\n \"delete_\" + entityLower + \"_Request\",\n OBJECT_MAPPER.valueToTree(ConnectionsClient.deleteOperationRequest()));\n break;\n case \"list\":\n paths.set(\n path,\n OBJECT_MAPPER.valueToTree(\n ConnectionsClient.listOperation(\n entityLower, jsonSchemaAsString, toolName, toolInstructions)));\n schemas.set(\n \"list_\" + entityLower + \"_Request\",\n OBJECT_MAPPER.valueToTree(ConnectionsClient.listOperationRequest()));\n break;\n case \"get\":\n paths.set(\n path,\n OBJECT_MAPPER.valueToTree(\n ConnectionsClient.getOperation(\n entityLower, jsonSchemaAsString, toolName, toolInstructions)));\n schemas.set(\n \"get_\" + entityLower + \"_Request\",\n OBJECT_MAPPER.valueToTree(ConnectionsClient.getOperationRequest()));\n break;\n default:\n throw new IllegalArgumentException(\n \"Invalid operation: \" + operation + \" for entity: \" + entity);\n }\n }\n }\n } else if (this.actions != null) {\n for (String action : this.actions) {\n ObjectNode actionDetails =\n OBJECT_MAPPER.valueToTree(connectionsClient.getActionSchema(action));\n\n JsonNode inputSchemaNode = actionDetails.path(\"inputSchema\");\n JsonNode outputSchemaNode = actionDetails.path(\"outputSchema\");\n\n String actionDisplayName = actionDetails.path(\"displayName\").asText(\"\").replace(\" \", \"\");\n String operation = \"EXECUTE_ACTION\";\n\n Map inputSchemaMap = OBJECT_MAPPER.treeToValue(inputSchemaNode, Map.class);\n Map outputSchemaMap =\n OBJECT_MAPPER.treeToValue(outputSchemaNode, Map.class);\n\n if (Objects.equals(action, \"ExecuteCustomQuery\")) {\n schemas.set(\n actionDisplayName + \"_Request\",\n OBJECT_MAPPER.valueToTree(ConnectionsClient.executeCustomQueryRequest()));\n operation = \"EXECUTE_QUERY\";\n } else {\n schemas.set(\n actionDisplayName + \"_Request\",\n OBJECT_MAPPER.valueToTree(ConnectionsClient.actionRequest(actionDisplayName)));\n schemas.set(\n \"connectorInputPayload_\" + actionDisplayName,\n OBJECT_MAPPER.valueToTree(connectionsClient.connectorPayload(inputSchemaMap)));\n }\n\n schemas.set(\n \"connectorOutputPayload_\" + actionDisplayName,\n OBJECT_MAPPER.valueToTree(connectionsClient.connectorPayload(outputSchemaMap)));\n schemas.set(\n actionDisplayName + \"_Response\",\n OBJECT_MAPPER.valueToTree(ConnectionsClient.actionResponse(actionDisplayName)));\n\n String path =\n String.format(\n \"/v2/projects/%s/locations/%s/integrations/%s:execute?triggerId=api_trigger/%s#%s\",\n this.project, this.location, integrationName, integrationName, action);\n\n paths.set(\n path,\n OBJECT_MAPPER.valueToTree(\n ConnectionsClient.getActionOperation(\n action, operation, actionDisplayName, toolName, toolInstructions)));\n }\n } else {\n throw new IllegalArgumentException(\n \"No entity operations or actions provided. Please provide at least one of them.\");\n }\n return connectorSpec;\n }\n\n String getOperationIdFromPathUrl(String openApiSchemaString, String pathUrl) throws Exception {\n JsonNode topLevelNode = OBJECT_MAPPER.readTree(openApiSchemaString);\n JsonNode specNode = topLevelNode.path(\"openApiSpec\");\n if (specNode.isMissingNode() || !specNode.isTextual()) {\n throw new IllegalArgumentException(\n \"Failed to get OpenApiSpec, please check the project and region for the integration.\");\n }\n JsonNode rootNode = OBJECT_MAPPER.readTree(specNode.asText());\n JsonNode paths = rootNode.path(\"paths\");\n\n Iterator> pathsFields = paths.fields();\n while (pathsFields.hasNext()) {\n Map.Entry pathEntry = pathsFields.next();\n String currentPath = pathEntry.getKey();\n if (!currentPath.equals(pathUrl)) {\n continue;\n }\n JsonNode pathItem = pathEntry.getValue();\n\n Iterator> methods = pathItem.fields();\n while (methods.hasNext()) {\n Map.Entry methodEntry = methods.next();\n JsonNode operationNode = methodEntry.getValue();\n\n if (operationNode.has(\"operationId\")) {\n return operationNode.path(\"operationId\").asText();\n }\n }\n }\n throw new Exception(\"Could not find operationId for pathUrl: \" + pathUrl);\n }\n\n ConnectionsClient createConnectionsClient() {\n return new ConnectionsClient(\n this.project, this.location, this.connection, this.httpExecutor, OBJECT_MAPPER);\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/agents/InvocationContext.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.agents;\n\nimport com.google.adk.artifacts.BaseArtifactService;\nimport com.google.adk.exceptions.LlmCallsLimitExceededException;\nimport com.google.adk.sessions.BaseSessionService;\nimport com.google.adk.sessions.Session;\nimport com.google.genai.types.Content;\nimport java.util.Objects;\nimport java.util.Optional;\nimport java.util.UUID;\nimport javax.annotation.Nullable;\n\n/** The context for an agent invocation. */\npublic class InvocationContext {\n\n private final BaseSessionService sessionService;\n private final BaseArtifactService artifactService;\n private final Optional liveRequestQueue;\n\n private Optional branch;\n private final String invocationId;\n private BaseAgent agent;\n private final Session session;\n\n private final Optional userContent;\n private final RunConfig runConfig;\n private boolean endInvocation;\n private final InvocationCostManager invocationCostManager = new InvocationCostManager();\n\n private InvocationContext(\n BaseSessionService sessionService,\n BaseArtifactService artifactService,\n Optional liveRequestQueue,\n Optional branch,\n String invocationId,\n BaseAgent agent,\n Session session,\n Optional userContent,\n RunConfig runConfig,\n boolean endInvocation) {\n this.sessionService = sessionService;\n this.artifactService = artifactService;\n this.liveRequestQueue = liveRequestQueue;\n this.branch = branch;\n this.invocationId = invocationId;\n this.agent = agent;\n this.session = session;\n this.userContent = userContent;\n this.runConfig = runConfig;\n this.endInvocation = endInvocation;\n }\n\n public static InvocationContext create(\n BaseSessionService sessionService,\n BaseArtifactService artifactService,\n String invocationId,\n BaseAgent agent,\n Session session,\n Content userContent,\n RunConfig runConfig) {\n return new InvocationContext(\n sessionService,\n artifactService,\n Optional.empty(),\n /* branch= */ Optional.empty(),\n invocationId,\n agent,\n session,\n Optional.ofNullable(userContent),\n runConfig,\n false);\n }\n\n public static InvocationContext create(\n BaseSessionService sessionService,\n BaseArtifactService artifactService,\n BaseAgent agent,\n Session session,\n LiveRequestQueue liveRequestQueue,\n RunConfig runConfig) {\n return new InvocationContext(\n sessionService,\n artifactService,\n Optional.ofNullable(liveRequestQueue),\n /* branch= */ Optional.empty(),\n InvocationContext.newInvocationContextId(),\n agent,\n session,\n Optional.empty(),\n runConfig,\n false);\n }\n\n public static InvocationContext copyOf(InvocationContext other) {\n return new InvocationContext(\n other.sessionService,\n other.artifactService,\n other.liveRequestQueue,\n other.branch,\n other.invocationId,\n other.agent,\n other.session,\n other.userContent,\n other.runConfig,\n other.endInvocation);\n }\n\n public BaseSessionService sessionService() {\n return sessionService;\n }\n\n public BaseArtifactService artifactService() {\n return artifactService;\n }\n\n public Optional liveRequestQueue() {\n return liveRequestQueue;\n }\n\n public String invocationId() {\n return invocationId;\n }\n\n public void branch(@Nullable String branch) {\n this.branch = Optional.ofNullable(branch);\n }\n\n public Optional branch() {\n return branch;\n }\n\n public BaseAgent agent() {\n return agent;\n }\n\n public void agent(BaseAgent agent) {\n this.agent = agent;\n }\n\n public Session session() {\n return session;\n }\n\n public Optional userContent() {\n return userContent;\n }\n\n public RunConfig runConfig() {\n return runConfig;\n }\n\n public boolean endInvocation() {\n return endInvocation;\n }\n\n public void setEndInvocation(boolean endInvocation) {\n this.endInvocation = endInvocation;\n }\n\n public String appName() {\n return session.appName();\n }\n\n public String userId() {\n return session.userId();\n }\n\n public static String newInvocationContextId() {\n return \"e-\" + UUID.randomUUID();\n }\n\n public void incrementLlmCallsCount() throws LlmCallsLimitExceededException {\n this.invocationCostManager.incrementAndEnforceLlmCallsLimit(this.runConfig);\n }\n\n private static class InvocationCostManager {\n private int numberOfLlmCalls = 0;\n\n public void incrementAndEnforceLlmCallsLimit(RunConfig runConfig)\n throws LlmCallsLimitExceededException {\n this.numberOfLlmCalls++;\n\n if (runConfig != null\n && runConfig.maxLlmCalls() > 0\n && this.numberOfLlmCalls > runConfig.maxLlmCalls()) {\n throw new LlmCallsLimitExceededException(\n \"Max number of llm calls limit of \" + runConfig.maxLlmCalls() + \" exceeded\");\n }\n }\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (!(o instanceof InvocationContext that)) {\n return false;\n }\n return endInvocation == that.endInvocation\n && Objects.equals(sessionService, that.sessionService)\n && Objects.equals(artifactService, that.artifactService)\n && Objects.equals(liveRequestQueue, that.liveRequestQueue)\n && Objects.equals(branch, that.branch)\n && Objects.equals(invocationId, that.invocationId)\n && Objects.equals(agent, that.agent)\n && Objects.equals(session, that.session)\n && Objects.equals(userContent, that.userContent)\n && Objects.equals(runConfig, that.runConfig);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(\n sessionService,\n artifactService,\n liveRequestQueue,\n branch,\n invocationId,\n agent,\n session,\n userContent,\n runConfig,\n endInvocation);\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/BaseTool.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools;\n\nimport static com.google.common.collect.ImmutableList.toImmutableList;\n\nimport com.google.adk.models.LlmRequest;\nimport com.google.common.collect.ImmutableList;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport com.google.genai.types.FunctionDeclaration;\nimport com.google.genai.types.GenerateContentConfig;\nimport com.google.genai.types.Tool;\nimport io.reactivex.rxjava3.core.Completable;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.Map;\nimport java.util.Optional;\nimport javax.annotation.Nonnull;\nimport org.jspecify.annotations.Nullable;\n\n/** The base class for all ADK tools. */\npublic abstract class BaseTool {\n private final String name;\n private final String description;\n private final boolean isLongRunning;\n\n protected BaseTool(@Nonnull String name, @Nonnull String description) {\n this(name, description, /* isLongRunning= */ false);\n }\n\n protected BaseTool(@Nonnull String name, @Nonnull String description, boolean isLongRunning) {\n this.name = name;\n this.description = description;\n this.isLongRunning = isLongRunning;\n }\n\n public String name() {\n return name;\n }\n\n public String description() {\n return description;\n }\n\n public boolean longRunning() {\n return isLongRunning;\n }\n\n /** Gets the {@link FunctionDeclaration} representation of this tool. */\n public Optional declaration() {\n return Optional.empty();\n }\n\n /** Calls a tool. */\n public Single> runAsync(Map args, ToolContext toolContext) {\n throw new UnsupportedOperationException(\"This method is not implemented.\");\n }\n\n /**\n * Processes the outgoing {@link LlmRequest.Builder}.\n *\n *

This implementation adds the current tool's {@link #declaration()} to the {@link\n * GenerateContentConfig} within the builder. If a tool with function declarations already exists,\n * the current tool's declaration is merged into it. Otherwise, a new tool definition with the\n * current tool's declaration is created. The current tool itself is also added to the builder's\n * internal list of tools. Override this method for processing the outgoing request.\n */\n @CanIgnoreReturnValue\n public Completable processLlmRequest(\n LlmRequest.Builder llmRequestBuilder, ToolContext toolContext) {\n if (declaration().isEmpty()) {\n return Completable.complete();\n }\n\n llmRequestBuilder.appendTools(ImmutableList.of(this));\n\n LlmRequest llmRequest = llmRequestBuilder.build();\n ImmutableList toolsWithoutFunctionDeclarations =\n findToolsWithoutFunctionDeclarations(llmRequest);\n Tool toolWithFunctionDeclarations = findToolWithFunctionDeclarations(llmRequest);\n // If LlmRequest GenerateContentConfig already has a function calling tool,\n // merge the function declarations.\n // Otherwise, add a new tool definition with function calling declaration..\n if (toolWithFunctionDeclarations == null) {\n toolWithFunctionDeclarations =\n Tool.builder().functionDeclarations(ImmutableList.of(declaration().get())).build();\n } else {\n toolWithFunctionDeclarations =\n toolWithFunctionDeclarations.toBuilder()\n .functionDeclarations(\n ImmutableList.builder()\n .addAll(\n toolWithFunctionDeclarations\n .functionDeclarations()\n .orElse(ImmutableList.of()))\n .add(declaration().get())\n .build())\n .build();\n }\n // Patch the GenerateContentConfig with the new tool definition.\n GenerateContentConfig generateContentConfig =\n llmRequest\n .config()\n .map(GenerateContentConfig::toBuilder)\n .orElse(GenerateContentConfig.builder())\n .tools(\n new ImmutableList.Builder()\n .addAll(toolsWithoutFunctionDeclarations)\n .add(toolWithFunctionDeclarations)\n .build())\n .build();\n llmRequestBuilder.config(generateContentConfig);\n return Completable.complete();\n }\n\n /**\n * Finds a tool in GenerateContentConfig that has function calling declarations, or returns null\n * otherwise.\n */\n private static @Nullable Tool findToolWithFunctionDeclarations(LlmRequest llmRequest) {\n return llmRequest\n .config()\n .flatMap(config -> config.tools())\n .flatMap(\n tools -> tools.stream().filter(t -> t.functionDeclarations().isPresent()).findFirst())\n .orElse(null);\n }\n\n /** Finds all tools in GenerateContentConfig that do not have function calling declarations. */\n private static ImmutableList findToolsWithoutFunctionDeclarations(LlmRequest llmRequest) {\n return llmRequest\n .config()\n .flatMap(config -> config.tools())\n .map(\n tools ->\n tools.stream()\n .filter(t -> t.functionDeclarations().isEmpty())\n .collect(toImmutableList()))\n .orElse(ImmutableList.of());\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/models/LlmRequest.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.models;\n\nimport static com.google.common.collect.ImmutableList.toImmutableList;\nimport static com.google.common.collect.ImmutableMap.toImmutableMap;\n\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonIgnore;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.databind.annotation.JsonDeserialize;\nimport com.google.adk.JsonBaseModel;\nimport com.google.adk.tools.BaseTool;\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.GenerateContentConfig;\nimport com.google.genai.types.LiveConnectConfig;\nimport com.google.genai.types.Part;\nimport com.google.genai.types.Schema;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.stream.Stream;\n\n/** Represents a request to be sent to the LLM. */\n@AutoValue\n@JsonDeserialize(builder = LlmRequest.Builder.class)\npublic abstract class LlmRequest extends JsonBaseModel {\n\n /**\n * Returns the name of the LLM model to be used. If not set, the default model of the LLM class\n * will be used.\n *\n * @return An optional string representing the model name.\n */\n @JsonProperty(\"model\")\n public abstract Optional model();\n\n /**\n * Returns the list of content sent to the LLM.\n *\n * @return A list of {@link Content} objects.\n */\n @JsonProperty(\"contents\")\n public abstract List contents();\n\n /**\n * Returns the configuration for content generation.\n *\n * @return An optional {@link GenerateContentConfig} object containing the generation settings.\n */\n @JsonProperty(\"config\")\n public abstract Optional config();\n\n /**\n * Returns the configuration for live connections. Populated using the RunConfig in the\n * InvocationContext.\n *\n * @return An optional {@link LiveConnectConfig} object containing the live connection settings.\n */\n @JsonProperty(\"liveConnectConfig\")\n public abstract LiveConnectConfig liveConnectConfig();\n\n /**\n * Returns a map of tools available to the LLM.\n *\n * @return A map where keys are tool names and values are {@link BaseTool} instances.\n */\n @JsonIgnore\n public abstract Map tools();\n\n /** returns the first system instruction text from the request if present. */\n @JsonIgnore\n public Optional getFirstSystemInstruction() {\n return this.config()\n .flatMap(GenerateContentConfig::systemInstruction)\n .flatMap(content -> content.parts().flatMap(partList -> partList.stream().findFirst()))\n .flatMap(Part::text);\n }\n\n /** Returns all system instruction texts from the request as an immutable list. */\n @JsonIgnore\n public ImmutableList getSystemInstructions() {\n return config()\n .flatMap(GenerateContentConfig::systemInstruction)\n .flatMap(Content::parts)\n .map(\n partList ->\n partList.stream()\n .map(Part::text)\n .flatMap(Optional::stream)\n .collect(toImmutableList()))\n .orElse(ImmutableList.of());\n }\n\n public static Builder builder() {\n return new AutoValue_LlmRequest.Builder()\n .tools(ImmutableMap.of())\n .contents(ImmutableList.of())\n .liveConnectConfig(LiveConnectConfig.builder().build());\n }\n\n public abstract Builder toBuilder();\n\n /** Builder for constructing {@link LlmRequest} instances. */\n @AutoValue.Builder\n public abstract static class Builder {\n\n @JsonCreator\n private static Builder create() {\n return builder();\n }\n\n @CanIgnoreReturnValue\n @JsonProperty(\"model\")\n public abstract Builder model(String model);\n\n @CanIgnoreReturnValue\n @JsonProperty(\"contents\")\n public abstract Builder contents(List contents);\n\n @CanIgnoreReturnValue\n @JsonProperty(\"config\")\n public abstract Builder config(GenerateContentConfig config);\n\n public abstract Optional config();\n\n @CanIgnoreReturnValue\n @JsonProperty(\"liveConnectConfig\")\n public abstract Builder liveConnectConfig(LiveConnectConfig liveConnectConfig);\n\n abstract LiveConnectConfig liveConnectConfig();\n\n @CanIgnoreReturnValue\n abstract Builder tools(Map tools);\n\n abstract Map tools();\n\n @CanIgnoreReturnValue\n public final Builder appendInstructions(List instructions) {\n if (instructions.isEmpty()) {\n return this;\n }\n GenerateContentConfig config = config().orElse(GenerateContentConfig.builder().build());\n ImmutableList.Builder parts = ImmutableList.builder();\n if (config.systemInstruction().isPresent()) {\n parts.addAll(config.systemInstruction().get().parts().orElse(ImmutableList.of()));\n }\n parts.addAll(\n instructions.stream()\n .map(instruction -> Part.builder().text(instruction).build())\n .collect(toImmutableList()));\n config(\n config.toBuilder()\n .systemInstruction(\n Content.builder()\n .parts(parts.build())\n .role(\n config\n .systemInstruction()\n .map(c -> c.role().orElse(\"user\"))\n .orElse(\"user\"))\n .build())\n .build());\n\n LiveConnectConfig liveConfig = liveConnectConfig();\n ImmutableList.Builder livePartsBuilder = ImmutableList.builder();\n\n if (liveConfig.systemInstruction().isPresent()) {\n livePartsBuilder.addAll(\n liveConfig.systemInstruction().get().parts().orElse(ImmutableList.of()));\n }\n\n livePartsBuilder.addAll(\n instructions.stream()\n .map(instruction -> Part.builder().text(instruction).build())\n .collect(toImmutableList()));\n\n return liveConnectConfig(\n liveConfig.toBuilder()\n .systemInstruction(\n Content.builder()\n .parts(livePartsBuilder.build())\n .role(\n liveConfig\n .systemInstruction()\n .map(c -> c.role().orElse(\"user\"))\n .orElse(\"user\"))\n .build())\n .build());\n }\n\n @CanIgnoreReturnValue\n public final Builder appendTools(List tools) {\n if (tools.isEmpty()) {\n return this;\n }\n return tools(\n ImmutableMap.builder()\n .putAll(\n Stream.concat(tools.stream(), tools().values().stream())\n .collect(\n toImmutableMap(\n BaseTool::name,\n tool -> tool,\n (tool1, tool2) -> {\n throw new IllegalArgumentException(\n String.format(\"Duplicate tool name: %s\", tool1.name()));\n })))\n .buildOrThrow());\n }\n\n /**\n * Sets the output schema for the LLM response. If set, The output content will always be a JSON\n * string that conforms to the schema.\n */\n @CanIgnoreReturnValue\n public final Builder outputSchema(Schema schema) {\n GenerateContentConfig config = config().orElse(GenerateContentConfig.builder().build());\n return config(\n config.toBuilder().responseSchema(schema).responseMimeType(\"application/json\").build());\n }\n\n public abstract LlmRequest build();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/applicationintegrationtoolset/IntegrationConnectorTool.java", "package com.google.adk.tools.applicationintegrationtoolset;\n\nimport static com.google.common.base.Strings.isNullOrEmpty;\nimport static java.nio.charset.StandardCharsets.UTF_8;\n\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.fasterxml.jackson.databind.node.ArrayNode;\nimport com.fasterxml.jackson.databind.node.ObjectNode;\nimport com.google.adk.tools.BaseTool;\nimport com.google.adk.tools.ToolContext;\nimport com.google.auth.oauth2.GoogleCredentials;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Streams;\nimport com.google.genai.types.FunctionDeclaration;\nimport com.google.genai.types.Schema;\nimport io.reactivex.rxjava3.core.Single;\nimport java.io.ByteArrayInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\nimport org.jspecify.annotations.Nullable;\n\n/** Application Integration Tool */\npublic class IntegrationConnectorTool extends BaseTool {\n\n private final String openApiSpec;\n private final String pathUrl;\n private final HttpExecutor httpExecutor;\n private final String connectionName;\n private final String serviceName;\n private final String host;\n private String entity;\n private String operation;\n private String action;\n private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();\n\n interface HttpExecutor {\n HttpResponse send(HttpRequest request, HttpResponse.BodyHandler responseBodyHandler)\n throws IOException, InterruptedException;\n\n String getToken() throws IOException;\n\n public HttpExecutor createExecutor(String serviceAccountJson);\n }\n\n static class DefaultHttpExecutor implements HttpExecutor {\n private final HttpClient client = HttpClient.newHttpClient();\n private final String serviceAccountJson;\n\n /** Default constructor for when no service account is specified. */\n DefaultHttpExecutor() {\n this(null);\n }\n\n /**\n * Constructor that accepts an optional service account JSON string.\n *\n * @param serviceAccountJson The service account key as a JSON string, or null.\n */\n DefaultHttpExecutor(@Nullable String serviceAccountJson) {\n this.serviceAccountJson = serviceAccountJson;\n }\n\n @Override\n public HttpResponse send(\n HttpRequest request, HttpResponse.BodyHandler responseBodyHandler)\n throws IOException, InterruptedException {\n return client.send(request, responseBodyHandler);\n }\n\n @Override\n public String getToken() throws IOException {\n GoogleCredentials credentials;\n\n if (this.serviceAccountJson != null && !this.serviceAccountJson.trim().isEmpty()) {\n try (InputStream is = new ByteArrayInputStream(this.serviceAccountJson.getBytes(UTF_8))) {\n credentials =\n GoogleCredentials.fromStream(is)\n .createScoped(\"https://www.googleapis.com/auth/cloud-platform\");\n } catch (IOException e) {\n throw new IOException(\"Failed to load credentials from service_account_json.\", e);\n }\n } else {\n try {\n credentials =\n GoogleCredentials.getApplicationDefault()\n .createScoped(\"https://www.googleapis.com/auth/cloud-platform\");\n } catch (IOException e) {\n throw new IOException(\n \"Please provide a service account or configure Application Default Credentials. To\"\n + \" set up ADC, see\"\n + \" https://cloud.google.com/docs/authentication/external/set-up-adc.\",\n e);\n }\n }\n\n credentials.refreshIfExpired();\n return credentials.getAccessToken().getTokenValue();\n }\n\n @Override\n public HttpExecutor createExecutor(String serviceAccountJson) {\n if (isNullOrEmpty(serviceAccountJson)) {\n return new DefaultHttpExecutor();\n } else {\n return new DefaultHttpExecutor(serviceAccountJson);\n }\n }\n }\n\n private static final ImmutableList EXCLUDE_FIELDS =\n ImmutableList.of(\"connectionName\", \"serviceName\", \"host\", \"entity\", \"operation\", \"action\");\n\n private static final ImmutableList OPTIONAL_FIELDS =\n ImmutableList.of(\"pageSize\", \"pageToken\", \"filter\", \"sortByColumns\");\n\n /** Constructor for Application Integration Tool for integration */\n IntegrationConnectorTool(\n String openApiSpec,\n String pathUrl,\n String toolName,\n String toolDescription,\n String serviceAccountJson) {\n this(\n openApiSpec,\n pathUrl,\n toolName,\n toolDescription,\n null,\n null,\n null,\n serviceAccountJson,\n new DefaultHttpExecutor().createExecutor(serviceAccountJson));\n }\n\n /**\n * Constructor for Application Integration Tool with connection name, service name, host, entity,\n * operation, and action\n */\n IntegrationConnectorTool(\n String openApiSpec,\n String pathUrl,\n String toolName,\n String toolDescription,\n String connectionName,\n String serviceName,\n String host,\n String serviceAccountJson) {\n this(\n openApiSpec,\n pathUrl,\n toolName,\n toolDescription,\n connectionName,\n serviceName,\n host,\n serviceAccountJson,\n new DefaultHttpExecutor().createExecutor(serviceAccountJson));\n }\n\n IntegrationConnectorTool(\n String openApiSpec,\n String pathUrl,\n String toolName,\n String toolDescription,\n @Nullable String connectionName,\n @Nullable String serviceName,\n @Nullable String host,\n @Nullable String serviceAccountJson,\n HttpExecutor httpExecutor) {\n super(toolName, toolDescription);\n this.openApiSpec = openApiSpec;\n this.pathUrl = pathUrl;\n this.connectionName = connectionName;\n this.serviceName = serviceName;\n this.host = host;\n this.httpExecutor = httpExecutor;\n }\n\n Schema toGeminiSchema(String openApiSchema, String operationId) throws Exception {\n String resolvedSchemaString = getResolvedRequestSchemaByOperationId(openApiSchema, operationId);\n return Schema.fromJson(resolvedSchemaString);\n }\n\n @Override\n public Optional declaration() {\n try {\n String operationId = getOperationIdFromPathUrl(openApiSpec, pathUrl);\n Schema parametersSchema = toGeminiSchema(openApiSpec, operationId);\n String operationDescription = getOperationDescription(openApiSpec, operationId);\n\n FunctionDeclaration declaration =\n FunctionDeclaration.builder()\n .name(operationId)\n .description(operationDescription)\n .parameters(parametersSchema)\n .build();\n return Optional.of(declaration);\n } catch (Exception e) {\n System.err.println(\"Failed to get OpenAPI spec: \" + e.getMessage());\n return Optional.empty();\n }\n }\n\n @Override\n public Single> runAsync(Map args, ToolContext toolContext) {\n if (this.connectionName != null) {\n args.put(\"connectionName\", this.connectionName);\n args.put(\"serviceName\", this.serviceName);\n args.put(\"host\", this.host);\n if (!isNullOrEmpty(this.entity)) {\n args.put(\"entity\", this.entity);\n } else if (!isNullOrEmpty(this.action)) {\n args.put(\"action\", this.action);\n }\n if (!isNullOrEmpty(this.operation)) {\n args.put(\"operation\", this.operation);\n }\n }\n\n return Single.fromCallable(\n () -> {\n try {\n String response = executeIntegration(args);\n return ImmutableMap.of(\"result\", response);\n } catch (Exception e) {\n System.err.println(\"Failed to execute integration: \" + e.getMessage());\n return ImmutableMap.of(\"error\", e.getMessage());\n }\n });\n }\n\n private String executeIntegration(Map args) throws Exception {\n String url = String.format(\"https://integrations.googleapis.com%s\", this.pathUrl);\n String jsonRequestBody;\n try {\n jsonRequestBody = OBJECT_MAPPER.writeValueAsString(args);\n } catch (IOException e) {\n throw new Exception(\"Error converting args to JSON: \" + e.getMessage(), e);\n }\n HttpRequest request =\n HttpRequest.newBuilder()\n .uri(URI.create(url))\n .header(\"Authorization\", \"Bearer \" + httpExecutor.getToken())\n .header(\"Content-Type\", \"application/json\")\n .POST(HttpRequest.BodyPublishers.ofString(jsonRequestBody))\n .build();\n HttpResponse response =\n httpExecutor.send(request, HttpResponse.BodyHandlers.ofString());\n\n if (response.statusCode() < 200 || response.statusCode() >= 300) {\n throw new Exception(\n \"Error executing integration. Status: \"\n + response.statusCode()\n + \" , Response: \"\n + response.body());\n }\n return response.body();\n }\n\n String getOperationIdFromPathUrl(String openApiSchemaString, String pathUrl) throws Exception {\n JsonNode topLevelNode = OBJECT_MAPPER.readTree(openApiSchemaString);\n JsonNode specNode = topLevelNode.path(\"openApiSpec\");\n if (specNode.isMissingNode() || !specNode.isTextual()) {\n throw new IllegalArgumentException(\n \"Failed to get OpenApiSpec, please check the project and region for the integration.\");\n }\n JsonNode rootNode = OBJECT_MAPPER.readTree(specNode.asText());\n JsonNode paths = rootNode.path(\"paths\");\n\n // Iterate through each path in the OpenAPI spec.\n Iterator> pathsFields = paths.fields();\n while (pathsFields.hasNext()) {\n Map.Entry pathEntry = pathsFields.next();\n String currentPath = pathEntry.getKey();\n if (!currentPath.equals(pathUrl)) {\n continue;\n }\n JsonNode pathItem = pathEntry.getValue();\n\n Iterator> methods = pathItem.fields();\n while (methods.hasNext()) {\n Map.Entry methodEntry = methods.next();\n JsonNode operationNode = methodEntry.getValue();\n // Set values for entity, operation, and action\n this.entity = \"\";\n this.operation = \"\";\n this.action = \"\";\n if (operationNode.has(\"x-entity\")) {\n this.entity = operationNode.path(\"x-entity\").asText();\n } else if (operationNode.has(\"x-action\")) {\n this.action = operationNode.path(\"x-action\").asText();\n }\n if (operationNode.has(\"x-operation\")) {\n this.operation = operationNode.path(\"x-operation\").asText();\n }\n // Get the operationId from the operationNode\n if (operationNode.has(\"operationId\")) {\n return operationNode.path(\"operationId\").asText();\n }\n }\n }\n throw new Exception(\"Could not find operationId for pathUrl: \" + pathUrl);\n }\n\n private String getResolvedRequestSchemaByOperationId(\n String openApiSchemaString, String operationId) throws Exception {\n JsonNode topLevelNode = OBJECT_MAPPER.readTree(openApiSchemaString);\n JsonNode specNode = topLevelNode.path(\"openApiSpec\");\n if (specNode.isMissingNode() || !specNode.isTextual()) {\n throw new IllegalArgumentException(\n \"Failed to get OpenApiSpec, please check the project and region for the integration.\");\n }\n JsonNode rootNode = OBJECT_MAPPER.readTree(specNode.asText());\n JsonNode operationNode = findOperationNodeById(rootNode, operationId);\n if (operationNode == null) {\n throw new Exception(\"Could not find operation with operationId: \" + operationId);\n }\n JsonNode requestSchemaNode =\n operationNode.path(\"requestBody\").path(\"content\").path(\"application/json\").path(\"schema\");\n\n if (requestSchemaNode.isMissingNode()) {\n throw new Exception(\"Could not find request body schema for operationId: \" + operationId);\n }\n\n JsonNode resolvedSchema = resolveRefs(requestSchemaNode, rootNode);\n\n if (resolvedSchema.isObject()) {\n ObjectNode schemaObject = (ObjectNode) resolvedSchema;\n\n // 1. Remove excluded fields from the 'properties' object.\n JsonNode propertiesNode = schemaObject.path(\"properties\");\n if (propertiesNode.isObject()) {\n ObjectNode propertiesObject = (ObjectNode) propertiesNode;\n for (String field : EXCLUDE_FIELDS) {\n propertiesObject.remove(field);\n }\n }\n\n // 2. Remove optional and excluded fields from the 'required' array.\n JsonNode requiredNode = schemaObject.path(\"required\");\n if (requiredNode.isArray()) {\n // Combine the lists of fields to remove\n List fieldsToRemove =\n Streams.concat(OPTIONAL_FIELDS.stream(), EXCLUDE_FIELDS.stream()).toList();\n\n // To safely remove items from a list while iterating, we must use an Iterator.\n ArrayNode requiredArray = (ArrayNode) requiredNode;\n Iterator elements = requiredArray.elements();\n while (elements.hasNext()) {\n JsonNode element = elements.next();\n if (element.isTextual() && fieldsToRemove.contains(element.asText())) {\n // This removes the current element from the underlying array.\n elements.remove();\n }\n }\n }\n }\n return OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(resolvedSchema);\n }\n\n private @Nullable JsonNode findOperationNodeById(JsonNode rootNode, String operationId) {\n JsonNode paths = rootNode.path(\"paths\");\n for (JsonNode pathItem : paths) {\n Iterator> methods = pathItem.fields();\n while (methods.hasNext()) {\n Map.Entry methodEntry = methods.next();\n JsonNode operationNode = methodEntry.getValue();\n if (operationNode.path(\"operationId\").asText().equals(operationId)) {\n return operationNode;\n }\n }\n }\n return null;\n }\n\n private JsonNode resolveRefs(JsonNode currentNode, JsonNode rootNode) {\n if (currentNode.isObject()) {\n ObjectNode objectNode = (ObjectNode) currentNode;\n if (objectNode.has(\"$ref\")) {\n String refPath = objectNode.get(\"$ref\").asText();\n if (refPath.isEmpty() || !refPath.startsWith(\"#/\")) {\n return objectNode;\n }\n JsonNode referencedNode = rootNode.at(refPath.substring(1));\n if (referencedNode.isMissingNode()) {\n return objectNode;\n }\n return resolveRefs(referencedNode, rootNode);\n } else {\n ObjectNode newObjectNode = OBJECT_MAPPER.createObjectNode();\n Iterator> fields = currentNode.fields();\n while (fields.hasNext()) {\n Map.Entry field = fields.next();\n newObjectNode.set(field.getKey(), resolveRefs(field.getValue(), rootNode));\n }\n return newObjectNode;\n }\n }\n return currentNode;\n }\n\n private String getOperationDescription(String openApiSchemaString, String operationId)\n throws Exception {\n JsonNode topLevelNode = OBJECT_MAPPER.readTree(openApiSchemaString);\n JsonNode specNode = topLevelNode.path(\"openApiSpec\");\n if (specNode.isMissingNode() || !specNode.isTextual()) {\n return \"\";\n }\n JsonNode rootNode = OBJECT_MAPPER.readTree(specNode.asText());\n JsonNode operationNode = findOperationNodeById(rootNode, operationId);\n if (operationNode == null) {\n return \"\";\n }\n return operationNode.path(\"summary\").asText();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/FunctionTool.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools;\n\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.genai.types.FunctionDeclaration;\nimport io.reactivex.rxjava3.core.Maybe;\nimport io.reactivex.rxjava3.core.Single;\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Modifier;\nimport java.lang.reflect.Parameter;\nimport java.lang.reflect.ParameterizedType;\nimport java.lang.reflect.Type;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\nimport javax.annotation.Nullable;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/** FunctionTool implements a customized function calling tool. */\npublic class FunctionTool extends BaseTool {\n private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();\n private static final Logger logger = LoggerFactory.getLogger(FunctionTool.class);\n\n @Nullable private final Object instance;\n private final Method func;\n private final FunctionDeclaration funcDeclaration;\n\n public static FunctionTool create(Object instance, Method func) {\n if (!areParametersAnnotatedWithSchema(func) && wasCompiledWithDefaultParameterNames(func)) {\n logger.error(\n \"Functions used in tools must have their parameters annotated with @Schema or at least\"\n + \" the code must be compiled with the -parameters flag as a fallback. Your function\"\n + \" tool will likely not work as expected and exit at runtime.\");\n }\n if (!Modifier.isStatic(func.getModifiers()) && !func.getDeclaringClass().isInstance(instance)) {\n throw new IllegalArgumentException(\n String.format(\n \"The instance provided is not an instance of the declaring class of the method.\"\n + \" Expected: %s, Actual: %s\",\n func.getDeclaringClass().getName(), instance.getClass().getName()));\n }\n return new FunctionTool(instance, func, /* isLongRunning= */ false);\n }\n\n public static FunctionTool create(Method func) {\n if (!areParametersAnnotatedWithSchema(func) && wasCompiledWithDefaultParameterNames(func)) {\n logger.error(\n \"Functions used in tools must have their parameters annotated with @Schema or at least\"\n + \" the code must be compiled with the -parameters flag as a fallback. Your function\"\n + \" tool will likely not work as expected and exit at runtime.\");\n }\n if (!Modifier.isStatic(func.getModifiers())) {\n throw new IllegalArgumentException(\"The method provided must be static.\");\n }\n return new FunctionTool(null, func, /* isLongRunning= */ false);\n }\n\n public static FunctionTool create(Class cls, String methodName) {\n for (Method method : cls.getMethods()) {\n if (method.getName().equals(methodName) && Modifier.isStatic(method.getModifiers())) {\n return create(null, method);\n }\n }\n throw new IllegalArgumentException(\n String.format(\"Static method %s not found in class %s.\", methodName, cls.getName()));\n }\n\n public static FunctionTool create(Object instance, String methodName) {\n Class cls = instance.getClass();\n for (Method method : cls.getMethods()) {\n if (method.getName().equals(methodName) && !Modifier.isStatic(method.getModifiers())) {\n return create(instance, method);\n }\n }\n throw new IllegalArgumentException(\n String.format(\"Instance method %s not found in class %s.\", methodName, cls.getName()));\n }\n\n private static boolean areParametersAnnotatedWithSchema(Method func) {\n for (Parameter parameter : func.getParameters()) {\n if (!parameter.isAnnotationPresent(Annotations.Schema.class)\n || parameter.getAnnotation(Annotations.Schema.class).name().isEmpty()) {\n return false;\n }\n }\n return true;\n }\n\n // Rough check to see if the code wasn't compiled with the -parameters flag.\n private static boolean wasCompiledWithDefaultParameterNames(Method func) {\n for (Parameter parameter : func.getParameters()) {\n String parameterName = parameter.getName();\n if (!parameterName.matches(\"arg\\\\d+\")) {\n return false;\n }\n }\n return true;\n }\n\n protected FunctionTool(@Nullable Object instance, Method func, boolean isLongRunning) {\n super(\n func.isAnnotationPresent(Annotations.Schema.class)\n && !func.getAnnotation(Annotations.Schema.class).name().isEmpty()\n ? func.getAnnotation(Annotations.Schema.class).name()\n : func.getName(),\n func.isAnnotationPresent(Annotations.Schema.class)\n ? func.getAnnotation(Annotations.Schema.class).description()\n : \"\",\n isLongRunning);\n boolean isStatic = Modifier.isStatic(func.getModifiers());\n if (isStatic && instance != null) {\n throw new IllegalArgumentException(\"Static function tool must not have an instance.\");\n } else if (!isStatic && instance == null) {\n throw new IllegalArgumentException(\"Instance function tool must have an instance.\");\n }\n\n this.instance = instance;\n this.func = func;\n this.funcDeclaration =\n FunctionCallingUtils.buildFunctionDeclaration(this.func, ImmutableList.of(\"toolContext\"));\n }\n\n @Override\n public Optional declaration() {\n return Optional.of(this.funcDeclaration);\n }\n\n @Override\n public Single> runAsync(Map args, ToolContext toolContext) {\n try {\n return this.call(args, toolContext).defaultIfEmpty(ImmutableMap.of());\n } catch (Exception e) {\n e.printStackTrace();\n return Single.just(ImmutableMap.of());\n }\n }\n\n @SuppressWarnings(\"unchecked\") // For tool parameter type casting.\n private Maybe> call(Map args, ToolContext toolContext)\n throws IllegalAccessException, InvocationTargetException {\n Parameter[] parameters = func.getParameters();\n Object[] arguments = new Object[parameters.length];\n for (int i = 0; i < parameters.length; i++) {\n String paramName =\n parameters[i].isAnnotationPresent(Annotations.Schema.class)\n && !parameters[i].getAnnotation(Annotations.Schema.class).name().isEmpty()\n ? parameters[i].getAnnotation(Annotations.Schema.class).name()\n : parameters[i].getName();\n if (paramName.equals(\"toolContext\")) {\n arguments[i] = toolContext;\n continue;\n }\n if (!args.containsKey(paramName)) {\n throw new IllegalArgumentException(\n String.format(\n \"The parameter '%s' was not found in the arguments provided by the model.\",\n paramName));\n }\n Class paramType = parameters[i].getType();\n Object argValue = args.get(paramName);\n if (paramType.equals(List.class)) {\n if (argValue instanceof List) {\n Type type =\n ((ParameterizedType) parameters[i].getParameterizedType())\n .getActualTypeArguments()[0];\n arguments[i] = createList((List) argValue, (Class) type);\n continue;\n }\n } else if (argValue instanceof Map) {\n arguments[i] = OBJECT_MAPPER.convertValue(argValue, paramType);\n continue;\n }\n arguments[i] = castValue(argValue, paramType);\n }\n Object result = func.invoke(instance, arguments);\n if (result == null) {\n return Maybe.empty();\n } else if (result instanceof Maybe) {\n return (Maybe>) result;\n } else if (result instanceof Single) {\n return ((Single>) result).toMaybe();\n } else {\n return Maybe.just((Map) result);\n }\n }\n\n private static List createList(List values, Class type) {\n List list = new ArrayList<>();\n // List of parameterized type is not supported.\n if (type == null) {\n return list;\n }\n Class cls = type;\n for (Object value : values) {\n if (cls == Integer.class\n || cls == Long.class\n || cls == Double.class\n || cls == Float.class\n || cls == Boolean.class\n || cls == String.class) {\n list.add(castValue(value, cls));\n } else {\n list.add(OBJECT_MAPPER.convertValue(value, type));\n }\n }\n return list;\n }\n\n private static Object castValue(Object value, Class type) {\n if (type.equals(Integer.class) || type.equals(int.class)) {\n if (value instanceof Integer) {\n return value;\n }\n }\n if (type.equals(Long.class) || type.equals(long.class)) {\n if (value instanceof Long || value instanceof Integer) {\n return value;\n }\n } else if (type.equals(Double.class) || type.equals(double.class)) {\n if (value instanceof Double d) {\n return d.doubleValue();\n }\n if (value instanceof Float f) {\n return f.doubleValue();\n }\n if (value instanceof Integer i) {\n return i.doubleValue();\n }\n if (value instanceof Long l) {\n return l.doubleValue();\n }\n } else if (type.equals(Float.class) || type.equals(float.class)) {\n if (value instanceof Double d) {\n return d.floatValue();\n }\n if (value instanceof Float f) {\n return f.floatValue();\n }\n if (value instanceof Integer i) {\n return i.floatValue();\n }\n if (value instanceof Long l) {\n return l.floatValue();\n }\n } else if (type.equals(Boolean.class) || type.equals(boolean.class)) {\n if (value instanceof Boolean) {\n return value;\n }\n } else if (type.equals(String.class)) {\n if (value instanceof String) {\n return value;\n }\n }\n return OBJECT_MAPPER.convertValue(value, type);\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/agents/CallbackContext.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.agents;\n\nimport com.google.adk.events.EventActions;\nimport com.google.adk.sessions.State;\nimport com.google.genai.types.Part;\nimport io.reactivex.rxjava3.core.Maybe;\nimport java.util.Optional;\n\n/** The context of various callbacks for an agent invocation. */\npublic class CallbackContext extends ReadonlyContext {\n\n protected EventActions eventActions;\n private final State state;\n\n /**\n * Initializes callback context.\n *\n * @param invocationContext Current invocation context.\n * @param eventActions Callback event actions.\n */\n public CallbackContext(InvocationContext invocationContext, EventActions eventActions) {\n super(invocationContext);\n this.eventActions = eventActions != null ? eventActions : EventActions.builder().build();\n this.state = new State(invocationContext.session().state(), this.eventActions.stateDelta());\n }\n\n /** Returns the delta-aware state of the current callback. */\n @Override\n public State state() {\n return state;\n }\n\n /** Returns the EventActions associated with this context. */\n public EventActions eventActions() {\n return eventActions;\n }\n\n /**\n * Loads an artifact from the artifact service associated with the current session.\n *\n * @param filename Artifact file name.\n * @param version Artifact version (optional).\n * @return loaded part, or empty if not found.\n * @throws IllegalStateException if the artifact service is not initialized.\n */\n public Maybe loadArtifact(String filename, Optional version) {\n if (invocationContext.artifactService() == null) {\n throw new IllegalStateException(\"Artifact service is not initialized.\");\n }\n return invocationContext\n .artifactService()\n .loadArtifact(\n invocationContext.appName(),\n invocationContext.userId(),\n invocationContext.session().id(),\n filename,\n version);\n }\n\n /**\n * Saves an artifact and records it as a delta for the current session.\n *\n * @param filename Artifact file name.\n * @param artifact Artifact content to save.\n * @throws IllegalStateException if the artifact service is not initialized.\n */\n public void saveArtifact(String filename, Part artifact) {\n if (invocationContext.artifactService() == null) {\n throw new IllegalStateException(\"Artifact service is not initialized.\");\n }\n var unused =\n invocationContext\n .artifactService()\n .saveArtifact(\n invocationContext.appName(),\n invocationContext.userId(),\n invocationContext.session().id(),\n filename,\n artifact);\n this.eventActions.artifactDelta().put(filename, artifact);\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/retrieval/VertexAiRagRetrieval.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools.retrieval;\n\nimport static com.google.common.collect.ImmutableList.toImmutableList;\n\nimport com.google.adk.models.LlmRequest;\nimport com.google.adk.tools.ToolContext;\nimport com.google.cloud.aiplatform.v1.RagContexts;\nimport com.google.cloud.aiplatform.v1.RagQuery;\nimport com.google.cloud.aiplatform.v1.RetrieveContextsRequest;\nimport com.google.cloud.aiplatform.v1.RetrieveContextsRequest.VertexRagStore.RagResource;\nimport com.google.cloud.aiplatform.v1.RetrieveContextsResponse;\nimport com.google.cloud.aiplatform.v1.VertexRagServiceClient;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport com.google.genai.types.GenerateContentConfig;\nimport com.google.genai.types.Retrieval;\nimport com.google.genai.types.Tool;\nimport com.google.genai.types.VertexRagStore;\nimport com.google.genai.types.VertexRagStoreRagResource;\nimport io.reactivex.rxjava3.core.Completable;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.List;\nimport java.util.Map;\nimport javax.annotation.Nonnull;\nimport javax.annotation.Nullable;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * A retrieval tool that fetches context from Vertex AI RAG.\n *\n *

This tool allows to retrieve relevant information based on a query using Vertex AI RAG\n * service. It supports configuration of rag resources and a vector distance threshold.\n */\npublic class VertexAiRagRetrieval extends BaseRetrievalTool {\n private static final Logger logger = LoggerFactory.getLogger(VertexAiRagRetrieval.class);\n private final VertexRagServiceClient vertexRagServiceClient;\n private final String parent;\n private final List ragResources;\n private final Double vectorDistanceThreshold;\n private final VertexRagStore vertexRagStore;\n private final RetrieveContextsRequest.VertexRagStore apiVertexRagStore;\n\n public VertexAiRagRetrieval(\n @Nonnull String name,\n @Nonnull String description,\n @Nonnull VertexRagServiceClient vertexRagServiceClient,\n @Nonnull String parent,\n @Nullable List ragResources,\n @Nullable Double vectorDistanceThreshold) {\n super(name, description);\n this.vertexRagServiceClient = vertexRagServiceClient;\n this.parent = parent;\n this.ragResources = ragResources;\n this.vectorDistanceThreshold = vectorDistanceThreshold;\n\n // For Gemini 2\n VertexRagStore.Builder vertexRagStoreBuilder = VertexRagStore.builder();\n if (this.ragResources != null) {\n vertexRagStoreBuilder.ragResources(\n this.ragResources.stream()\n .map(\n ragResource ->\n VertexRagStoreRagResource.builder()\n .ragCorpus(ragResource.getRagCorpus())\n .build())\n .collect(toImmutableList()));\n }\n if (this.vectorDistanceThreshold != null) {\n vertexRagStoreBuilder.vectorDistanceThreshold(this.vectorDistanceThreshold);\n }\n this.vertexRagStore = vertexRagStoreBuilder.build();\n\n // For runAsync\n RetrieveContextsRequest.VertexRagStore.Builder apiVertexRagStoreBuilder =\n RetrieveContextsRequest.VertexRagStore.newBuilder();\n if (this.ragResources != null) {\n apiVertexRagStoreBuilder.addAllRagResources(this.ragResources);\n }\n if (this.vectorDistanceThreshold != null) {\n apiVertexRagStoreBuilder.setVectorDistanceThreshold(this.vectorDistanceThreshold);\n }\n this.apiVertexRagStore = apiVertexRagStoreBuilder.build();\n }\n\n @Override\n @CanIgnoreReturnValue\n public Completable processLlmRequest(\n LlmRequest.Builder llmRequestBuilder, ToolContext toolContext) {\n LlmRequest llmRequest = llmRequestBuilder.build();\n // Use Gemini built-in Vertex AI RAG tool for Gemini 2 models or when using Vertex AI API Model\n boolean useVertexAi = Boolean.parseBoolean(System.getenv(\"GOOGLE_GENAI_USE_VERTEXAI\"));\n if (useVertexAi\n && (llmRequest.model().isPresent() && llmRequest.model().get().startsWith(\"gemini-2\"))) {\n GenerateContentConfig config =\n llmRequest.config().orElse(GenerateContentConfig.builder().build());\n ImmutableList.Builder toolsBuilder = ImmutableList.builder();\n if (config.tools().isPresent()) {\n toolsBuilder.addAll(config.tools().get());\n }\n toolsBuilder.add(\n Tool.builder()\n .retrieval(Retrieval.builder().vertexRagStore(this.vertexRagStore).build())\n .build());\n logger.info(\n \"Using Gemini built-in Vertex AI RAG tool for model: {}\", llmRequest.model().get());\n llmRequestBuilder.config(config.toBuilder().tools(toolsBuilder.build()).build());\n return Completable.complete();\n } else {\n // Add the function declaration to the tools\n return super.processLlmRequest(llmRequestBuilder, toolContext);\n }\n }\n\n @Override\n public Single> runAsync(Map args, ToolContext toolContext) {\n String query = (String) args.get(\"query\");\n logger.info(\"VertexAiRagRetrieval.runAsync called with query: {}\", query);\n return Single.fromCallable(\n () -> {\n logger.info(\"Retrieving context for query: {}\", query);\n RetrieveContextsRequest retrieveContextsRequest =\n RetrieveContextsRequest.newBuilder()\n .setParent(this.parent)\n .setQuery(RagQuery.newBuilder().setText(query))\n .setVertexRagStore(this.apiVertexRagStore)\n .build();\n logger.info(\"Request to VertexRagService: {}\", retrieveContextsRequest);\n RetrieveContextsResponse response =\n this.vertexRagServiceClient.retrieveContexts(retrieveContextsRequest);\n logger.info(\"Response from VertexRagService: {}\", response);\n if (response.getContexts().getContextsList().isEmpty()) {\n logger.warn(\"No matching result found for query: {}\", query);\n return ImmutableMap.of(\n \"response\",\n String.format(\n \"No matching result found with the config: resources: %s\", this.ragResources));\n } else {\n logger.info(\n \"Found {} matching results for query: {}\",\n response.getContexts().getContextsCount(),\n query);\n ImmutableList contexts =\n response.getContexts().getContextsList().stream()\n .map(RagContexts.Context::getText)\n .collect(toImmutableList());\n logger.info(\"Returning contexts: {}\", contexts);\n return ImmutableMap.of(\"response\", contexts);\n }\n });\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/applicationintegrationtoolset/ConnectionsClient.java", "package com.google.adk.tools.applicationintegrationtoolset;\n\nimport static com.google.common.base.Strings.isNullOrEmpty;\n\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.google.adk.tools.applicationintegrationtoolset.IntegrationConnectorTool.HttpExecutor;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport java.io.IOException;\nimport java.net.URI;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Objects;\n\n/**\n * Utility class for interacting with the Google Cloud Connectors API.\n *\n *

This class provides methods to fetch connection details, schemas for entities and actions, and\n * to generate OpenAPI specifications for creating tools based on these connections.\n */\npublic class ConnectionsClient {\n\n private final String project;\n private final String location;\n private final String connection;\n private static final String CONNECTOR_URL = \"https://connectors.googleapis.com\";\n private final HttpExecutor httpExecutor;\n private final ObjectMapper objectMapper;\n\n /** Represents details of a connection. */\n public static class ConnectionDetails {\n public String name;\n public String serviceName;\n public String host;\n }\n\n /** Represents the schema and available operations for an entity. */\n public static class EntitySchemaAndOperations {\n public Map schema;\n public List operations;\n }\n\n /** Represents the schema for an action. */\n public static class ActionSchema {\n public Map inputSchema;\n public Map outputSchema;\n public String description;\n public String displayName;\n }\n\n /**\n * Initializes the ConnectionsClient.\n *\n * @param project The Google Cloud project ID.\n * @param location The Google Cloud location (e.g., us-central1).\n * @param connection The connection name.\n */\n public ConnectionsClient(\n String project,\n String location,\n String connection,\n HttpExecutor httpExecutor,\n ObjectMapper objectMapper) {\n this.project = project;\n this.location = location;\n this.connection = connection;\n this.httpExecutor = httpExecutor;\n this.objectMapper = objectMapper;\n }\n\n /**\n * Retrieves service details for a given connection.\n *\n * @return A {@link ConnectionDetails} object with the connection's info.\n * @throws IOException If there is an issue with network communication or credentials.\n * @throws InterruptedException If the thread is interrupted during the API call.\n */\n public ConnectionDetails getConnectionDetails() throws IOException, InterruptedException {\n String url =\n String.format(\n \"%s/v1/projects/%s/locations/%s/connections/%s?view=BASIC\",\n CONNECTOR_URL, project, location, connection);\n\n HttpResponse response = executeApiCall(url);\n Map connectionData = parseJson(response.body());\n\n ConnectionDetails details = new ConnectionDetails();\n details.name = (String) connectionData.getOrDefault(\"name\", \"\");\n details.serviceName = (String) connectionData.getOrDefault(\"serviceDirectory\", \"\");\n details.host = (String) connectionData.getOrDefault(\"host\", \"\");\n if (details.host != null && !details.host.isEmpty()) {\n details.serviceName = (String) connectionData.getOrDefault(\"tlsServiceDirectory\", \"\");\n }\n return details;\n }\n\n /**\n * Retrieves the JSON schema and available operations for a given entity.\n *\n * @param entity The entity name.\n * @return A {@link EntitySchemaAndOperations} object.\n * @throws IOException If there is an issue with network communication or credentials.\n * @throws InterruptedException If the thread is interrupted during polling.\n */\n @SuppressWarnings(\"unchecked\")\n public EntitySchemaAndOperations getEntitySchemaAndOperations(String entity)\n throws IOException, InterruptedException {\n String url =\n String.format(\n \"%s/v1/projects/%s/locations/%s/connections/%s/connectionSchemaMetadata:getEntityType?entityId=%s\",\n CONNECTOR_URL, project, location, connection, entity);\n\n HttpResponse initialResponse = executeApiCall(url);\n String operationId = (String) parseJson(initialResponse.body()).get(\"name\");\n\n if (isNullOrEmpty(operationId)) {\n throw new IOException(\"Failed to get operation ID for entity: \" + entity);\n }\n\n Map operationResponse = pollOperation(operationId);\n Map responseData =\n (Map) operationResponse.getOrDefault(\"response\", ImmutableMap.of());\n\n Map schema =\n (Map) responseData.getOrDefault(\"jsonSchema\", ImmutableMap.of());\n List operations =\n (List) responseData.getOrDefault(\"operations\", ImmutableList.of());\n EntitySchemaAndOperations entitySchemaAndOperations = new EntitySchemaAndOperations();\n entitySchemaAndOperations.schema = schema;\n entitySchemaAndOperations.operations = operations;\n return entitySchemaAndOperations;\n }\n\n /**\n * Retrieves the input and output JSON schema for a given action.\n *\n * @param action The action name.\n * @return An {@link ActionSchema} object.\n * @throws IOException If there is an issue with network communication or credentials.\n * @throws InterruptedException If the thread is interrupted during polling.\n */\n @SuppressWarnings(\"unchecked\")\n public ActionSchema getActionSchema(String action) throws IOException, InterruptedException {\n String url =\n String.format(\n \"%s/v1/projects/%s/locations/%s/connections/%s/connectionSchemaMetadata:getAction?actionId=%s\",\n CONNECTOR_URL, project, location, connection, action);\n\n HttpResponse initialResponse = executeApiCall(url);\n String operationId = (String) parseJson(initialResponse.body()).get(\"name\");\n\n if (isNullOrEmpty(operationId)) {\n throw new IOException(\"Failed to get operation ID for action: \" + action);\n }\n\n Map operationResponse = pollOperation(operationId);\n Map responseData =\n (Map) operationResponse.getOrDefault(\"response\", ImmutableMap.of());\n\n ActionSchema actionSchema = new ActionSchema();\n actionSchema.inputSchema =\n (Map) responseData.getOrDefault(\"inputJsonSchema\", ImmutableMap.of());\n actionSchema.outputSchema =\n (Map) responseData.getOrDefault(\"outputJsonSchema\", ImmutableMap.of());\n actionSchema.description = (String) responseData.getOrDefault(\"description\", \"\");\n actionSchema.displayName = (String) responseData.getOrDefault(\"displayName\", \"\");\n\n return actionSchema;\n }\n\n private HttpResponse executeApiCall(String url) throws IOException, InterruptedException {\n HttpRequest request =\n HttpRequest.newBuilder()\n .uri(URI.create(url))\n .header(\"Content-Type\", \"application/json\")\n .header(\"Authorization\", \"Bearer \" + httpExecutor.getToken())\n .GET()\n .build();\n\n HttpResponse response =\n httpExecutor.send(request, HttpResponse.BodyHandlers.ofString());\n\n if (response.statusCode() >= 400) {\n String body = response.body();\n if (response.statusCode() == 400 || response.statusCode() == 404) {\n throw new IllegalArgumentException(\n String.format(\n \"Invalid request. Please check the provided values of project(%s), location(%s),\"\n + \" connection(%s). Error: %s\",\n project, location, connection, body));\n }\n if (response.statusCode() == 401 || response.statusCode() == 403) {\n throw new SecurityException(\n String.format(\"Permission error (status %d): %s\", response.statusCode(), body));\n }\n throw new IOException(\n String.format(\"API call failed with status %d: %s\", response.statusCode(), body));\n }\n return response;\n }\n\n private Map pollOperation(String operationId)\n throws IOException, InterruptedException {\n boolean operationDone = false;\n Map operationResponse = null;\n\n while (!operationDone) {\n String getOperationUrl = String.format(\"%s/v1/%s\", CONNECTOR_URL, operationId);\n HttpResponse response = executeApiCall(getOperationUrl);\n operationResponse = parseJson(response.body());\n\n Object doneObj = operationResponse.get(\"done\");\n if (doneObj instanceof Boolean b) {\n operationDone = b;\n }\n\n if (!operationDone) {\n Thread.sleep(1000);\n }\n }\n return operationResponse;\n }\n\n /**\n * Converts a JSON Schema dictionary to an OpenAPI schema dictionary.\n *\n * @param jsonSchema The input JSON schema map.\n * @return The converted OpenAPI schema map.\n */\n public Map convertJsonSchemaToOpenApiSchema(Map jsonSchema) {\n Map openapiSchema = new HashMap<>();\n\n if (jsonSchema.containsKey(\"description\")) {\n openapiSchema.put(\"description\", jsonSchema.get(\"description\"));\n }\n\n if (jsonSchema.containsKey(\"type\")) {\n Object type = jsonSchema.get(\"type\");\n if (type instanceof List) {\n List typeList = (List) type;\n if (typeList.contains(\"null\")) {\n openapiSchema.put(\"nullable\", true);\n typeList.stream()\n .filter(t -> t instanceof String && !t.equals(\"null\"))\n .findFirst()\n .ifPresent(t -> openapiSchema.put(\"type\", t));\n } else if (!typeList.isEmpty()) {\n openapiSchema.put(\"type\", typeList.get(0));\n }\n } else {\n openapiSchema.put(\"type\", type);\n }\n }\n if (Objects.equals(openapiSchema.get(\"type\"), \"object\")\n && jsonSchema.containsKey(\"properties\")) {\n @SuppressWarnings(\"unchecked\")\n Map> properties =\n (Map>) jsonSchema.get(\"properties\");\n Map convertedProperties = new HashMap<>();\n for (Map.Entry> entry : properties.entrySet()) {\n convertedProperties.put(entry.getKey(), convertJsonSchemaToOpenApiSchema(entry.getValue()));\n }\n openapiSchema.put(\"properties\", convertedProperties);\n } else if (Objects.equals(openapiSchema.get(\"type\"), \"array\")\n && jsonSchema.containsKey(\"items\")) {\n @SuppressWarnings(\"unchecked\")\n Map itemsSchema = (Map) jsonSchema.get(\"items\");\n openapiSchema.put(\"items\", convertJsonSchemaToOpenApiSchema(itemsSchema));\n }\n\n return openapiSchema;\n }\n\n public Map connectorPayload(Map jsonSchema) {\n return convertJsonSchemaToOpenApiSchema(jsonSchema);\n }\n\n private Map parseJson(String json) throws IOException {\n return objectMapper.readValue(json, new TypeReference<>() {});\n }\n\n public static ImmutableMap getConnectorBaseSpec() {\n return ImmutableMap.ofEntries(\n Map.entry(\"openapi\", \"3.0.1\"),\n Map.entry(\n \"info\",\n ImmutableMap.of(\n \"title\", \"ExecuteConnection\",\n \"description\", \"This tool can execute a query on connection\",\n \"version\", \"4\")),\n Map.entry(\n \"servers\",\n ImmutableList.of(ImmutableMap.of(\"url\", \"https://integrations.googleapis.com\"))),\n Map.entry(\n \"security\",\n ImmutableList.of(\n ImmutableMap.of(\n \"google_auth\",\n ImmutableList.of(\"https://www.googleapis.com/auth/cloud-platform\")))),\n Map.entry(\"paths\", ImmutableMap.of()),\n Map.entry(\n \"components\",\n ImmutableMap.ofEntries(\n Map.entry(\n \"schemas\",\n ImmutableMap.ofEntries(\n Map.entry(\n \"operation\",\n ImmutableMap.of(\n \"type\", \"string\",\n \"default\", \"LIST_ENTITIES\",\n \"description\",\n \"Operation to execute. Possible values are LIST_ENTITIES,\"\n + \" GET_ENTITY, CREATE_ENTITY, UPDATE_ENTITY, DELETE_ENTITY\"\n + \" in case of entities. EXECUTE_ACTION in case of\"\n + \" actions. and EXECUTE_QUERY in case of custom\"\n + \" queries.\")),\n Map.entry(\n \"entityId\",\n ImmutableMap.of(\"type\", \"string\", \"description\", \"Name of the entity\")),\n Map.entry(\"connectorInputPayload\", ImmutableMap.of(\"type\", \"object\")),\n Map.entry(\n \"filterClause\",\n ImmutableMap.of(\n \"type\", \"string\",\n \"default\", \"\",\n \"description\", \"WHERE clause in SQL query\")),\n Map.entry(\n \"pageSize\",\n ImmutableMap.of(\n \"type\", \"integer\",\n \"default\", 50,\n \"description\", \"Number of entities to return in the response\")),\n Map.entry(\n \"pageToken\",\n ImmutableMap.of(\n \"type\", \"string\",\n \"default\", \"\",\n \"description\", \"Page token to return the next page of entities\")),\n Map.entry(\n \"connectionName\",\n ImmutableMap.of(\n \"type\", \"string\",\n \"default\", \"\",\n \"description\", \"Connection resource name to run the query for\")),\n Map.entry(\n \"serviceName\",\n ImmutableMap.of(\n \"type\", \"string\",\n \"default\", \"\",\n \"description\", \"Service directory for the connection\")),\n Map.entry(\n \"host\",\n ImmutableMap.of(\n \"type\", \"string\",\n \"default\", \"\",\n \"description\", \"Host name incase of tls service directory\")),\n Map.entry(\n \"entity\",\n ImmutableMap.of(\n \"type\", \"string\",\n \"default\", \"Issues\",\n \"description\", \"Entity to run the query for\")),\n Map.entry(\n \"action\",\n ImmutableMap.of(\n \"type\", \"string\",\n \"default\", \"ExecuteCustomQuery\",\n \"description\", \"Action to run the query for\")),\n Map.entry(\n \"query\",\n ImmutableMap.of(\n \"type\", \"string\",\n \"default\", \"\",\n \"description\", \"Custom Query to execute on the connection\")),\n Map.entry(\n \"timeout\",\n ImmutableMap.of(\n \"type\", \"integer\",\n \"default\", 120,\n \"description\", \"Timeout in seconds for execution of custom query\")),\n Map.entry(\n \"sortByColumns\",\n ImmutableMap.of(\n \"type\",\n \"array\",\n \"items\",\n ImmutableMap.of(\"type\", \"string\"),\n \"default\",\n ImmutableList.of(),\n \"description\",\n \"Column to sort the results by\")),\n Map.entry(\"connectorOutputPayload\", ImmutableMap.of(\"type\", \"object\")),\n Map.entry(\"nextPageToken\", ImmutableMap.of(\"type\", \"string\")),\n Map.entry(\n \"execute-connector_Response\",\n ImmutableMap.of(\n \"required\", ImmutableList.of(\"connectorOutputPayload\"),\n \"type\", \"object\",\n \"properties\",\n ImmutableMap.of(\n \"connectorOutputPayload\",\n ImmutableMap.of(\n \"$ref\", \"#/components/schemas/connectorOutputPayload\"),\n \"nextPageToken\",\n ImmutableMap.of(\n \"$ref\", \"#/components/schemas/nextPageToken\")))))),\n Map.entry(\n \"securitySchemes\",\n ImmutableMap.of(\n \"google_auth\",\n ImmutableMap.of(\n \"type\",\n \"oauth2\",\n \"flows\",\n ImmutableMap.of(\n \"implicit\",\n ImmutableMap.of(\n \"authorizationUrl\",\n \"https://accounts.google.com/o/oauth2/auth\",\n \"scopes\",\n ImmutableMap.of(\n \"https://www.googleapis.com/auth/cloud-platform\",\n \"Auth for google cloud services\")))))))));\n }\n\n public static ImmutableMap getActionOperation(\n String action,\n String operation,\n String actionDisplayName,\n String toolName,\n String toolInstructions) {\n String description = \"Use this tool to execute \" + action;\n if (Objects.equals(operation, \"EXECUTE_QUERY\")) {\n description +=\n \" Use pageSize = 50 and timeout = 120 until user specifies a different value\"\n + \" otherwise. If user provides a query in natural language, convert it to SQL query\"\n + \" and then execute it using the tool.\";\n }\n\n return ImmutableMap.of(\n \"post\",\n ImmutableMap.ofEntries(\n Map.entry(\"summary\", actionDisplayName),\n Map.entry(\"description\", description + \" \" + toolInstructions),\n Map.entry(\"operationId\", toolName + \"_\" + actionDisplayName),\n Map.entry(\"x-action\", action),\n Map.entry(\"x-operation\", operation),\n Map.entry(\n \"requestBody\",\n ImmutableMap.of(\n \"content\",\n ImmutableMap.of(\n \"application/json\",\n ImmutableMap.of(\n \"schema\",\n ImmutableMap.of(\n \"$ref\",\n String.format(\n \"#/components/schemas/%s_Request\", actionDisplayName)))))),\n Map.entry(\n \"responses\",\n ImmutableMap.of(\n \"200\",\n ImmutableMap.of(\n \"description\",\n \"Success response\",\n \"content\",\n ImmutableMap.of(\n \"application/json\",\n ImmutableMap.of(\n \"schema\",\n ImmutableMap.of(\n \"$ref\",\n String.format(\n \"#/components/schemas/%s_Response\",\n actionDisplayName)))))))));\n }\n\n public static ImmutableMap listOperation(\n String entity, String schemaAsString, String toolName, String toolInstructions) {\n return ImmutableMap.of(\n \"post\",\n ImmutableMap.ofEntries(\n Map.entry(\"summary\", \"List \" + entity),\n Map.entry(\n \"description\",\n String.format(\n \"Returns the list of %s data. If the page token was available in the response,\"\n + \" let users know there are more records available. Ask if the user wants\"\n + \" to fetch the next page of results. When passing filter use the\"\n + \" following format: `field_name1='value1' AND field_name2='value2'`. %s\",\n entity, toolInstructions)),\n Map.entry(\"x-operation\", \"LIST_ENTITIES\"),\n Map.entry(\"x-entity\", entity),\n Map.entry(\"operationId\", toolName + \"_list_\" + entity),\n Map.entry(\n \"requestBody\",\n ImmutableMap.of(\n \"content\",\n ImmutableMap.of(\n \"application/json\",\n ImmutableMap.of(\n \"schema\",\n ImmutableMap.of(\n \"$ref\", \"#/components/schemas/list_\" + entity + \"_Request\"))))),\n Map.entry(\n \"responses\",\n ImmutableMap.of(\n \"200\",\n ImmutableMap.of(\n \"description\",\n \"Success response\",\n \"content\",\n ImmutableMap.of(\n \"application/json\",\n ImmutableMap.of(\n \"schema\",\n ImmutableMap.of(\n \"description\",\n String.format(\n \"Returns a list of %s of json schema: %s\",\n entity, schemaAsString),\n \"$ref\",\n \"#/components/schemas/execute-connector_Response\"))))))));\n }\n\n public static ImmutableMap getOperation(\n String entity, String schemaAsString, String toolName, String toolInstructions) {\n return ImmutableMap.of(\n \"post\",\n ImmutableMap.ofEntries(\n Map.entry(\"summary\", \"Get \" + entity),\n Map.entry(\n \"description\",\n String.format(\"Returns the details of the %s. %s\", entity, toolInstructions)),\n Map.entry(\"operationId\", toolName + \"_get_\" + entity),\n Map.entry(\"x-operation\", \"GET_ENTITY\"),\n Map.entry(\"x-entity\", entity),\n Map.entry(\n \"requestBody\",\n ImmutableMap.of(\n \"content\",\n ImmutableMap.of(\n \"application/json\",\n ImmutableMap.of(\n \"schema\",\n ImmutableMap.of(\n \"$ref\", \"#/components/schemas/get_\" + entity + \"_Request\"))))),\n Map.entry(\n \"responses\",\n ImmutableMap.of(\n \"200\",\n ImmutableMap.of(\n \"description\",\n \"Success response\",\n \"content\",\n ImmutableMap.of(\n \"application/json\",\n ImmutableMap.of(\n \"schema\",\n ImmutableMap.of(\n \"description\",\n String.format(\n \"Returns %s of json schema: %s\", entity, schemaAsString),\n \"$ref\",\n \"#/components/schemas/execute-connector_Response\"))))))));\n }\n\n public static ImmutableMap createOperation(\n String entity, String toolName, String toolInstructions) {\n return ImmutableMap.of(\n \"post\",\n ImmutableMap.ofEntries(\n Map.entry(\"summary\", \"Creates a new \" + entity),\n Map.entry(\n \"description\", String.format(\"Creates a new %s. %s\", entity, toolInstructions)),\n Map.entry(\"x-operation\", \"CREATE_ENTITY\"),\n Map.entry(\"x-entity\", entity),\n Map.entry(\"operationId\", toolName + \"_create_\" + entity),\n Map.entry(\n \"requestBody\",\n ImmutableMap.of(\n \"content\",\n ImmutableMap.of(\n \"application/json\",\n ImmutableMap.of(\n \"schema\",\n ImmutableMap.of(\n \"$ref\", \"#/components/schemas/create_\" + entity + \"_Request\"))))),\n Map.entry(\n \"responses\",\n ImmutableMap.of(\n \"200\",\n ImmutableMap.of(\n \"description\",\n \"Success response\",\n \"content\",\n ImmutableMap.of(\n \"application/json\",\n ImmutableMap.of(\n \"schema\",\n ImmutableMap.of(\n \"$ref\",\n \"#/components/schemas/execute-connector_Response\"))))))));\n }\n\n public static ImmutableMap updateOperation(\n String entity, String toolName, String toolInstructions) {\n return ImmutableMap.of(\n \"post\",\n ImmutableMap.ofEntries(\n Map.entry(\"summary\", \"Updates the \" + entity),\n Map.entry(\"description\", String.format(\"Updates the %s. %s\", entity, toolInstructions)),\n Map.entry(\"x-operation\", \"UPDATE_ENTITY\"),\n Map.entry(\"x-entity\", entity),\n Map.entry(\"operationId\", toolName + \"_update_\" + entity),\n Map.entry(\n \"requestBody\",\n ImmutableMap.of(\n \"content\",\n ImmutableMap.of(\n \"application/json\",\n ImmutableMap.of(\n \"schema\",\n ImmutableMap.of(\n \"$ref\", \"#/components/schemas/update_\" + entity + \"_Request\"))))),\n Map.entry(\n \"responses\",\n ImmutableMap.of(\n \"200\",\n ImmutableMap.of(\n \"description\",\n \"Success response\",\n \"content\",\n ImmutableMap.of(\n \"application/json\",\n ImmutableMap.of(\n \"schema\",\n ImmutableMap.of(\n \"$ref\",\n \"#/components/schemas/execute-connector_Response\"))))))));\n }\n\n public static ImmutableMap deleteOperation(\n String entity, String toolName, String toolInstructions) {\n return ImmutableMap.of(\n \"post\",\n ImmutableMap.ofEntries(\n Map.entry(\"summary\", \"Delete the \" + entity),\n Map.entry(\"description\", String.format(\"Deletes the %s. %s\", entity, toolInstructions)),\n Map.entry(\"x-operation\", \"DELETE_ENTITY\"),\n Map.entry(\"x-entity\", entity),\n Map.entry(\"operationId\", toolName + \"_delete_\" + entity),\n Map.entry(\n \"requestBody\",\n ImmutableMap.of(\n \"content\",\n ImmutableMap.of(\n \"application/json\",\n ImmutableMap.of(\n \"schema\",\n ImmutableMap.of(\n \"$ref\", \"#/components/schemas/delete_\" + entity + \"_Request\"))))),\n Map.entry(\n \"responses\",\n ImmutableMap.of(\n \"200\",\n ImmutableMap.of(\n \"description\",\n \"Success response\",\n \"content\",\n ImmutableMap.of(\n \"application/json\",\n ImmutableMap.of(\n \"schema\",\n ImmutableMap.of(\n \"$ref\",\n \"#/components/schemas/execute-connector_Response\"))))))));\n }\n\n public static ImmutableMap createOperationRequest(String entity) {\n return ImmutableMap.of(\n \"type\",\n \"object\",\n \"required\",\n ImmutableList.of(\n \"connectorInputPayload\",\n \"operation\",\n \"connectionName\",\n \"serviceName\",\n \"host\",\n \"entity\"),\n \"properties\",\n ImmutableMap.ofEntries(\n Map.entry(\n \"connectorInputPayload\",\n ImmutableMap.of(\"$ref\", \"#/components/schemas/connectorInputPayload_\" + entity)),\n Map.entry(\"operation\", ImmutableMap.of(\"$ref\", \"#/components/schemas/operation\")),\n Map.entry(\n \"connectionName\", ImmutableMap.of(\"$ref\", \"#/components/schemas/connectionName\")),\n Map.entry(\"serviceName\", ImmutableMap.of(\"$ref\", \"#/components/schemas/serviceName\")),\n Map.entry(\"host\", ImmutableMap.of(\"$ref\", \"#/components/schemas/host\")),\n Map.entry(\"entity\", ImmutableMap.of(\"$ref\", \"#/components/schemas/entity\"))));\n }\n\n public static ImmutableMap updateOperationRequest(String entity) {\n return ImmutableMap.of(\n \"type\",\n \"object\",\n \"required\",\n ImmutableList.of(\n \"connectorInputPayload\",\n \"entityId\",\n \"operation\",\n \"connectionName\",\n \"serviceName\",\n \"host\",\n \"entity\"),\n \"properties\",\n ImmutableMap.ofEntries(\n Map.entry(\n \"connectorInputPayload\",\n ImmutableMap.of(\"$ref\", \"#/components/schemas/connectorInputPayload_\" + entity)),\n Map.entry(\"entityId\", ImmutableMap.of(\"$ref\", \"#/components/schemas/entityId\")),\n Map.entry(\"operation\", ImmutableMap.of(\"$ref\", \"#/components/schemas/operation\")),\n Map.entry(\n \"connectionName\", ImmutableMap.of(\"$ref\", \"#/components/schemas/connectionName\")),\n Map.entry(\"serviceName\", ImmutableMap.of(\"$ref\", \"#/components/schemas/serviceName\")),\n Map.entry(\"host\", ImmutableMap.of(\"$ref\", \"#/components/schemas/host\")),\n Map.entry(\"entity\", ImmutableMap.of(\"$ref\", \"#/components/schemas/entity\")),\n Map.entry(\n \"filterClause\", ImmutableMap.of(\"$ref\", \"#/components/schemas/filterClause\"))));\n }\n\n public static ImmutableMap getOperationRequest() {\n return ImmutableMap.of(\n \"type\",\n \"object\",\n \"required\",\n ImmutableList.of(\n \"entityId\", \"operation\", \"connectionName\", \"serviceName\", \"host\", \"entity\"),\n \"properties\",\n ImmutableMap.ofEntries(\n Map.entry(\"entityId\", ImmutableMap.of(\"$ref\", \"#/components/schemas/entityId\")),\n Map.entry(\"operation\", ImmutableMap.of(\"$ref\", \"#/components/schemas/operation\")),\n Map.entry(\n \"connectionName\", ImmutableMap.of(\"$ref\", \"#/components/schemas/connectionName\")),\n Map.entry(\"serviceName\", ImmutableMap.of(\"$ref\", \"#/components/schemas/serviceName\")),\n Map.entry(\"host\", ImmutableMap.of(\"$ref\", \"#/components/schemas/host\")),\n Map.entry(\"entity\", ImmutableMap.of(\"$ref\", \"#/components/schemas/entity\"))));\n }\n\n public static ImmutableMap deleteOperationRequest() {\n return ImmutableMap.of(\n \"type\",\n \"object\",\n \"required\",\n ImmutableList.of(\n \"entityId\", \"operation\", \"connectionName\", \"serviceName\", \"host\", \"entity\"),\n \"properties\",\n ImmutableMap.ofEntries(\n Map.entry(\"entityId\", ImmutableMap.of(\"$ref\", \"#/components/schemas/entityId\")),\n Map.entry(\"operation\", ImmutableMap.of(\"$ref\", \"#/components/schemas/operation\")),\n Map.entry(\n \"connectionName\", ImmutableMap.of(\"$ref\", \"#/components/schemas/connectionName\")),\n Map.entry(\"serviceName\", ImmutableMap.of(\"$ref\", \"#/components/schemas/serviceName\")),\n Map.entry(\"host\", ImmutableMap.of(\"$ref\", \"#/components/schemas/host\")),\n Map.entry(\"entity\", ImmutableMap.of(\"$ref\", \"#/components/schemas/entity\")),\n Map.entry(\n \"filterClause\", ImmutableMap.of(\"$ref\", \"#/components/schemas/filterClause\"))));\n }\n\n public static ImmutableMap listOperationRequest() {\n return ImmutableMap.of(\n \"type\",\n \"object\",\n \"required\",\n ImmutableList.of(\"operation\", \"connectionName\", \"serviceName\", \"host\", \"entity\"),\n \"properties\",\n ImmutableMap.ofEntries(\n Map.entry(\"filterClause\", ImmutableMap.of(\"$ref\", \"#/components/schemas/filterClause\")),\n Map.entry(\"pageSize\", ImmutableMap.of(\"$ref\", \"#/components/schemas/pageSize\")),\n Map.entry(\"pageToken\", ImmutableMap.of(\"$ref\", \"#/components/schemas/pageToken\")),\n Map.entry(\"operation\", ImmutableMap.of(\"$ref\", \"#/components/schemas/operation\")),\n Map.entry(\n \"connectionName\", ImmutableMap.of(\"$ref\", \"#/components/schemas/connectionName\")),\n Map.entry(\"serviceName\", ImmutableMap.of(\"$ref\", \"#/components/schemas/serviceName\")),\n Map.entry(\"host\", ImmutableMap.of(\"$ref\", \"#/components/schemas/host\")),\n Map.entry(\"entity\", ImmutableMap.of(\"$ref\", \"#/components/schemas/entity\")),\n Map.entry(\n \"sortByColumns\", ImmutableMap.of(\"$ref\", \"#/components/schemas/sortByColumns\"))));\n }\n\n public static ImmutableMap actionRequest(String action) {\n return ImmutableMap.of(\n \"type\",\n \"object\",\n \"required\",\n ImmutableList.of(\n \"operation\",\n \"connectionName\",\n \"serviceName\",\n \"host\",\n \"action\",\n \"connectorInputPayload\"),\n \"properties\",\n ImmutableMap.ofEntries(\n Map.entry(\"operation\", ImmutableMap.of(\"$ref\", \"#/components/schemas/operation\")),\n Map.entry(\n \"connectionName\", ImmutableMap.of(\"$ref\", \"#/components/schemas/connectionName\")),\n Map.entry(\"serviceName\", ImmutableMap.of(\"$ref\", \"#/components/schemas/serviceName\")),\n Map.entry(\"host\", ImmutableMap.of(\"$ref\", \"#/components/schemas/host\")),\n Map.entry(\"action\", ImmutableMap.of(\"$ref\", \"#/components/schemas/action\")),\n Map.entry(\n \"connectorInputPayload\",\n ImmutableMap.of(\"$ref\", \"#/components/schemas/connectorInputPayload_\" + action))));\n }\n\n public static ImmutableMap actionResponse(String action) {\n return ImmutableMap.of(\n \"type\",\n \"object\",\n \"properties\",\n ImmutableMap.of(\n \"connectorOutputPayload\",\n ImmutableMap.of(\"$ref\", \"#/components/schemas/connectorOutputPayload_\" + action)));\n }\n\n public static ImmutableMap executeCustomQueryRequest() {\n return ImmutableMap.of(\n \"type\",\n \"object\",\n \"required\",\n ImmutableList.of(\n \"operation\",\n \"connectionName\",\n \"serviceName\",\n \"host\",\n \"action\",\n \"query\",\n \"timeout\",\n \"pageSize\"),\n \"properties\",\n ImmutableMap.ofEntries(\n Map.entry(\"operation\", ImmutableMap.of(\"$ref\", \"#/components/schemas/operation\")),\n Map.entry(\n \"connectionName\", ImmutableMap.of(\"$ref\", \"#/components/schemas/connectionName\")),\n Map.entry(\"serviceName\", ImmutableMap.of(\"$ref\", \"#/components/schemas/serviceName\")),\n Map.entry(\"host\", ImmutableMap.of(\"$ref\", \"#/components/schemas/host\")),\n Map.entry(\"action\", ImmutableMap.of(\"$ref\", \"#/components/schemas/action\")),\n Map.entry(\"query\", ImmutableMap.of(\"$ref\", \"#/components/schemas/query\")),\n Map.entry(\"timeout\", ImmutableMap.of(\"$ref\", \"#/components/schemas/timeout\")),\n Map.entry(\"pageSize\", ImmutableMap.of(\"$ref\", \"#/components/schemas/pageSize\"))));\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/ToolContext.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools;\n\nimport com.google.adk.agents.CallbackContext;\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.artifacts.ListArtifactsResponse;\nimport com.google.adk.events.EventActions;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.List;\nimport java.util.Optional;\n\n/** ToolContext object provides a structured context for executing tools or functions. */\npublic class ToolContext extends CallbackContext {\n private Optional functionCallId = Optional.empty();\n\n private ToolContext(\n InvocationContext invocationContext,\n EventActions eventActions,\n Optional functionCallId) {\n super(invocationContext, eventActions);\n this.functionCallId = functionCallId;\n }\n\n public EventActions actions() {\n return this.eventActions;\n }\n\n public void setActions(EventActions actions) {\n this.eventActions = actions;\n }\n\n public Optional functionCallId() {\n return functionCallId;\n }\n\n public void functionCallId(String functionCallId) {\n this.functionCallId = Optional.ofNullable(functionCallId);\n }\n\n @SuppressWarnings(\"unused\")\n private void requestCredential() {\n // TODO: b/414678311 - Implement credential request logic. Make this public.\n throw new UnsupportedOperationException(\"Credential request not implemented yet.\");\n }\n\n @SuppressWarnings(\"unused\")\n private void getAuthResponse() {\n // TODO: b/414678311 - Implement auth response retrieval logic. Make this public.\n throw new UnsupportedOperationException(\"Auth response retrieval not implemented yet.\");\n }\n\n @SuppressWarnings(\"unused\")\n private void searchMemory() {\n // TODO: b/414680316 - Implement search memory logic. Make this public.\n throw new UnsupportedOperationException(\"Search memory not implemented yet.\");\n }\n\n /** Lists the filenames of the artifacts attached to the current session. */\n public Single> listArtifacts() {\n if (invocationContext.artifactService() == null) {\n throw new IllegalStateException(\"Artifact service is not initialized.\");\n }\n return invocationContext\n .artifactService()\n .listArtifactKeys(\n invocationContext.session().appName(),\n invocationContext.session().userId(),\n invocationContext.session().id())\n .map(ListArtifactsResponse::filenames);\n }\n\n public static Builder builder(InvocationContext invocationContext) {\n return new Builder(invocationContext);\n }\n\n public Builder toBuilder() {\n return new Builder(invocationContext)\n .actions(eventActions)\n .functionCallId(functionCallId.orElse(null));\n }\n\n /** Builder for {@link ToolContext}. */\n public static final class Builder {\n private final InvocationContext invocationContext;\n private EventActions eventActions = EventActions.builder().build(); // Default empty actions\n private Optional functionCallId = Optional.empty();\n\n private Builder(InvocationContext invocationContext) {\n this.invocationContext = invocationContext;\n }\n\n @CanIgnoreReturnValue\n public Builder actions(EventActions actions) {\n this.eventActions = actions;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder functionCallId(String functionCallId) {\n this.functionCallId = Optional.ofNullable(functionCallId);\n return this;\n }\n\n public ToolContext build() {\n return new ToolContext(invocationContext, eventActions, functionCallId);\n }\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/sessions/ApiClient.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.StandardSystemProperty.JAVA_VERSION;\n\nimport com.google.auth.oauth2.GoogleCredentials;\nimport com.google.common.base.Ascii;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.genai.errors.GenAiIOException;\nimport com.google.genai.types.HttpOptions;\nimport java.io.IOException;\nimport java.time.Duration;\nimport java.util.Map;\nimport java.util.Optional;\nimport okhttp3.OkHttpClient;\nimport org.jspecify.annotations.Nullable;\n\n/** Interface for an API client which issues HTTP requests to the GenAI APIs. */\nabstract class ApiClient {\n OkHttpClient httpClient;\n // For Google AI APIs\n final Optional apiKey;\n // For Vertex AI APIs\n final Optional project;\n final Optional location;\n final Optional credentials;\n HttpOptions httpOptions;\n final boolean vertexAI;\n\n /** Constructs an ApiClient for Google AI APIs. */\n ApiClient(Optional apiKey, Optional customHttpOptions) {\n checkNotNull(apiKey, \"API Key cannot be null\");\n checkNotNull(customHttpOptions, \"customHttpOptions cannot be null\");\n\n try {\n this.apiKey = Optional.of(apiKey.orElse(System.getenv(\"GOOGLE_API_KEY\")));\n } catch (NullPointerException e) {\n throw new IllegalArgumentException(\n \"API key must either be provided or set in the environment variable\" + \" GOOGLE_API_KEY.\",\n e);\n }\n\n this.project = Optional.empty();\n this.location = Optional.empty();\n this.credentials = Optional.empty();\n this.vertexAI = false;\n\n this.httpOptions = defaultHttpOptions(/* vertexAI= */ false, this.location);\n\n if (customHttpOptions.isPresent()) {\n applyHttpOptions(customHttpOptions.get());\n }\n\n this.httpClient = createHttpClient(httpOptions.timeout());\n }\n\n ApiClient(\n Optional project,\n Optional location,\n Optional credentials,\n Optional customHttpOptions) {\n checkNotNull(project, \"project cannot be null\");\n checkNotNull(location, \"location cannot be null\");\n checkNotNull(credentials, \"credentials cannot be null\");\n checkNotNull(customHttpOptions, \"customHttpOptions cannot be null\");\n\n try {\n this.project = Optional.of(project.orElse(System.getenv(\"GOOGLE_CLOUD_PROJECT\")));\n } catch (NullPointerException e) {\n throw new IllegalArgumentException(\n \"Project must either be provided or set in the environment variable\"\n + \" GOOGLE_CLOUD_PROJECT.\",\n e);\n }\n if (this.project.get().isEmpty()) {\n throw new IllegalArgumentException(\"Project must not be empty.\");\n }\n\n try {\n this.location = Optional.of(location.orElse(System.getenv(\"GOOGLE_CLOUD_LOCATION\")));\n } catch (NullPointerException e) {\n throw new IllegalArgumentException(\n \"Location must either be provided or set in the environment variable\"\n + \" GOOGLE_CLOUD_LOCATION.\",\n e);\n }\n if (this.location.get().isEmpty()) {\n throw new IllegalArgumentException(\"Location must not be empty.\");\n }\n\n this.credentials = Optional.of(credentials.orElseGet(this::defaultCredentials));\n\n this.httpOptions = defaultHttpOptions(/* vertexAI= */ true, this.location);\n\n if (customHttpOptions.isPresent()) {\n applyHttpOptions(customHttpOptions.get());\n }\n this.apiKey = Optional.empty();\n this.vertexAI = true;\n this.httpClient = createHttpClient(httpOptions.timeout());\n }\n\n private OkHttpClient createHttpClient(Optional timeout) {\n OkHttpClient.Builder builder = new OkHttpClient().newBuilder();\n if (timeout.isPresent()) {\n builder.connectTimeout(Duration.ofMillis(timeout.get()));\n }\n return builder.build();\n }\n\n /** Sends a Http request given the http method, path, and request json string. */\n public abstract ApiResponse request(String httpMethod, String path, String requestJson);\n\n /** Returns the library version. */\n static String libraryVersion() {\n // TODO: Automate revisions to the SDK library version.\n String libraryLabel = \"google-genai-sdk/0.1.0\";\n String languageLabel = \"gl-java/\" + JAVA_VERSION.value();\n return libraryLabel + \" \" + languageLabel;\n }\n\n /** Returns whether the client is using Vertex AI APIs. */\n public boolean vertexAI() {\n return vertexAI;\n }\n\n /** Returns the project ID for Vertex AI APIs. */\n public @Nullable String project() {\n return project.orElse(null);\n }\n\n /** Returns the location for Vertex AI APIs. */\n public @Nullable String location() {\n return location.orElse(null);\n }\n\n /** Returns the API key for Google AI APIs. */\n public @Nullable String apiKey() {\n return apiKey.orElse(null);\n }\n\n /** Returns the HttpClient for API calls. */\n OkHttpClient httpClient() {\n return httpClient;\n }\n\n private Optional> getTimeoutHeader(HttpOptions httpOptionsToApply) {\n if (httpOptionsToApply.timeout().isPresent()) {\n int timeoutInSeconds = (int) Math.ceil((double) httpOptionsToApply.timeout().get() / 1000.0);\n // TODO(b/329147724): Document the usage of X-Server-Timeout header.\n return Optional.of(ImmutableMap.of(\"X-Server-Timeout\", Integer.toString(timeoutInSeconds)));\n }\n return Optional.empty();\n }\n\n private void applyHttpOptions(HttpOptions httpOptionsToApply) {\n HttpOptions.Builder mergedHttpOptionsBuilder = this.httpOptions.toBuilder();\n if (httpOptionsToApply.baseUrl().isPresent()) {\n mergedHttpOptionsBuilder.baseUrl(httpOptionsToApply.baseUrl().get());\n }\n if (httpOptionsToApply.apiVersion().isPresent()) {\n mergedHttpOptionsBuilder.apiVersion(httpOptionsToApply.apiVersion().get());\n }\n if (httpOptionsToApply.timeout().isPresent()) {\n mergedHttpOptionsBuilder.timeout(httpOptionsToApply.timeout().get());\n }\n if (httpOptionsToApply.headers().isPresent()) {\n ImmutableMap mergedHeaders =\n ImmutableMap.builder()\n .putAll(httpOptionsToApply.headers().orElse(ImmutableMap.of()))\n .putAll(this.httpOptions.headers().orElse(ImmutableMap.of()))\n .putAll(getTimeoutHeader(httpOptionsToApply).orElse(ImmutableMap.of()))\n .buildOrThrow();\n mergedHttpOptionsBuilder.headers(mergedHeaders);\n }\n this.httpOptions = mergedHttpOptionsBuilder.build();\n }\n\n static HttpOptions defaultHttpOptions(boolean vertexAI, Optional location) {\n ImmutableMap.Builder defaultHeaders = ImmutableMap.builder();\n defaultHeaders\n .put(\"Content-Type\", \"application/json\")\n .put(\"user-agent\", libraryVersion())\n .put(\"x-goog-api-client\", libraryVersion());\n\n HttpOptions.Builder defaultHttpOptionsBuilder =\n HttpOptions.builder().headers(defaultHeaders.buildOrThrow());\n\n if (vertexAI && location.isPresent()) {\n defaultHttpOptionsBuilder\n .baseUrl(\n Ascii.equalsIgnoreCase(location.get(), \"global\")\n ? \"https://aiplatform.googleapis.com\"\n : String.format(\"https://%s-aiplatform.googleapis.com\", location.get()))\n .apiVersion(\"v1beta1\");\n } else if (vertexAI && location.isEmpty()) {\n throw new IllegalArgumentException(\"Location must be provided for Vertex AI APIs.\");\n } else {\n defaultHttpOptionsBuilder\n .baseUrl(\"https://generativelanguage.googleapis.com\")\n .apiVersion(\"v1beta\");\n }\n return defaultHttpOptionsBuilder.build();\n }\n\n GoogleCredentials defaultCredentials() {\n try {\n return GoogleCredentials.getApplicationDefault()\n .createScoped(\"https://www.googleapis.com/auth/cloud-platform\");\n } catch (IOException e) {\n throw new GenAiIOException(\n \"Failed to get application default credentials, please explicitly provide credentials.\",\n e);\n }\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/FunctionCallingUtils.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools;\n\nimport static com.google.common.base.Preconditions.checkArgument;\n\nimport com.fasterxml.jackson.databind.BeanDescription;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition;\nimport com.google.adk.JsonBaseModel;\nimport com.google.common.base.Strings;\nimport com.google.genai.types.FunctionDeclaration;\nimport com.google.genai.types.Schema;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Parameter;\nimport java.lang.reflect.ParameterizedType;\nimport java.lang.reflect.Type;\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\n\n/** Utility class for function calling. */\npublic final class FunctionCallingUtils {\n\n private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();\n\n public static FunctionDeclaration buildFunctionDeclaration(\n Method func, List ignoreParams) {\n String name =\n func.isAnnotationPresent(Annotations.Schema.class)\n && !func.getAnnotation(Annotations.Schema.class).name().isEmpty()\n ? func.getAnnotation(Annotations.Schema.class).name()\n : func.getName();\n FunctionDeclaration.Builder builder = FunctionDeclaration.builder().name(name);\n if (func.isAnnotationPresent(Annotations.Schema.class)\n && !func.getAnnotation(Annotations.Schema.class).description().isEmpty()) {\n builder.description(func.getAnnotation(Annotations.Schema.class).description());\n }\n List required = new ArrayList<>();\n Map properties = new LinkedHashMap<>();\n for (Parameter param : func.getParameters()) {\n String paramName =\n param.isAnnotationPresent(Annotations.Schema.class)\n && !param.getAnnotation(Annotations.Schema.class).name().isEmpty()\n ? param.getAnnotation(Annotations.Schema.class).name()\n : param.getName();\n if (ignoreParams.contains(paramName)) {\n continue;\n }\n required.add(paramName);\n properties.put(paramName, buildSchemaFromParameter(param));\n }\n builder.parameters(\n Schema.builder().required(required).properties(properties).type(\"OBJECT\").build());\n\n Type returnType = func.getGenericReturnType();\n if (returnType != Void.TYPE) {\n Type realReturnType = returnType;\n if (returnType instanceof ParameterizedType) {\n ParameterizedType parameterizedReturnType = (ParameterizedType) returnType;\n String returnTypeName = ((Class) parameterizedReturnType.getRawType()).getName();\n if (returnTypeName.equals(\"io.reactivex.rxjava3.core.Maybe\")\n || returnTypeName.equals(\"io.reactivex.rxjava3.core.Single\")) {\n returnType = parameterizedReturnType.getActualTypeArguments()[0];\n if (returnType instanceof ParameterizedType) {\n ParameterizedType maybeParameterizedType = (ParameterizedType) returnType;\n returnTypeName = ((Class) maybeParameterizedType.getRawType()).getName();\n }\n }\n if (returnTypeName.equals(\"java.util.Map\")\n || returnTypeName.equals(\"com.google.common.collect.ImmutableMap\")) {\n return builder.response(buildSchemaFromType(returnType)).build();\n }\n }\n throw new IllegalArgumentException(\n \"Return type should be Map or Maybe or Single, but it was \"\n + realReturnType.getTypeName());\n }\n return builder.build();\n }\n\n static FunctionDeclaration buildFunctionDeclaration(JsonBaseModel func, String description) {\n // Create function declaration through json string.\n String jsonString = func.toJson();\n checkArgument(!Strings.isNullOrEmpty(jsonString), \"Input String can't be null or empty.\");\n FunctionDeclaration declaration = FunctionDeclaration.fromJson(jsonString);\n declaration = declaration.toBuilder().description(description).build();\n if (declaration.name().isEmpty() || declaration.name().get().isEmpty()) {\n throw new IllegalArgumentException(\"name field must be present.\");\n }\n return declaration;\n }\n\n private static Schema buildSchemaFromParameter(Parameter param) {\n Schema.Builder builder = Schema.builder();\n if (param.isAnnotationPresent(Annotations.Schema.class)\n && !param.getAnnotation(Annotations.Schema.class).description().isEmpty()) {\n builder.description(param.getAnnotation(Annotations.Schema.class).description());\n }\n switch (param.getType().getName()) {\n case \"java.lang.String\" -> builder.type(\"STRING\");\n case \"boolean\", \"java.lang.Boolean\" -> builder.type(\"BOOLEAN\");\n case \"int\", \"java.lang.Integer\" -> builder.type(\"INTEGER\");\n case \"double\", \"java.lang.Double\", \"float\", \"java.lang.Float\", \"long\", \"java.lang.Long\" ->\n builder.type(\"NUMBER\");\n case \"java.util.List\" ->\n builder\n .type(\"ARRAY\")\n .items(\n buildSchemaFromType(\n ((ParameterizedType) param.getParameterizedType())\n .getActualTypeArguments()[0]));\n case \"java.util.Map\" -> builder.type(\"OBJECT\");\n default -> {\n BeanDescription beanDescription =\n OBJECT_MAPPER\n .getSerializationConfig()\n .introspect(OBJECT_MAPPER.constructType(param.getType()));\n Map properties = new LinkedHashMap<>();\n for (BeanPropertyDefinition property : beanDescription.findProperties()) {\n properties.put(property.getName(), buildSchemaFromType(property.getRawPrimaryType()));\n }\n builder.type(\"OBJECT\").properties(properties);\n }\n }\n return builder.build();\n }\n\n public static Schema buildSchemaFromType(Type type) {\n Schema.Builder builder = Schema.builder();\n if (type instanceof ParameterizedType parameterizedType) {\n switch (((Class) parameterizedType.getRawType()).getName()) {\n case \"java.util.List\" ->\n builder\n .type(\"ARRAY\")\n .items(buildSchemaFromType(parameterizedType.getActualTypeArguments()[0]));\n case \"java.util.Map\", \"com.google.common.collect.ImmutableMap\" -> builder.type(\"OBJECT\");\n default -> throw new IllegalArgumentException(\"Unsupported generic type: \" + type);\n }\n } else if (type instanceof Class clazz) {\n switch (clazz.getName()) {\n case \"java.lang.String\" -> builder.type(\"STRING\");\n case \"boolean\", \"java.lang.Boolean\" -> builder.type(\"BOOLEAN\");\n case \"int\", \"java.lang.Integer\" -> builder.type(\"INTEGER\");\n case \"double\", \"java.lang.Double\", \"float\", \"java.lang.Float\", \"long\", \"java.lang.Long\" ->\n builder.type(\"NUMBER\");\n case \"java.util.Map\", \"com.google.common.collect.ImmutableMap\" -> builder.type(\"OBJECT\");\n default -> {\n BeanDescription beanDescription =\n OBJECT_MAPPER.getSerializationConfig().introspect(OBJECT_MAPPER.constructType(type));\n Map properties = new LinkedHashMap<>();\n for (BeanPropertyDefinition property : beanDescription.findProperties()) {\n properties.put(property.getName(), buildSchemaFromType(property.getRawPrimaryType()));\n }\n builder.type(\"OBJECT\").properties(properties);\n }\n }\n }\n return builder.build();\n }\n\n private FunctionCallingUtils() {}\n}\n"], ["/adk-java/dev/src/main/java/com/google/adk/web/AgentGraphGenerator.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.web;\n\nimport com.google.adk.agents.BaseAgent;\nimport com.google.adk.agents.LlmAgent;\nimport com.google.adk.tools.AgentTool;\nimport com.google.adk.tools.BaseTool;\nimport com.google.adk.tools.FunctionTool;\nimport com.google.adk.tools.retrieval.BaseRetrievalTool;\nimport guru.nidi.graphviz.attribute.Arrow;\nimport guru.nidi.graphviz.attribute.Color;\nimport guru.nidi.graphviz.attribute.Label;\nimport guru.nidi.graphviz.attribute.Rank;\nimport guru.nidi.graphviz.attribute.Shape;\nimport guru.nidi.graphviz.attribute.Style;\nimport guru.nidi.graphviz.engine.Format;\nimport guru.nidi.graphviz.engine.Graphviz;\nimport guru.nidi.graphviz.model.Factory;\nimport guru.nidi.graphviz.model.Link;\nimport guru.nidi.graphviz.model.MutableGraph;\nimport guru.nidi.graphviz.model.MutableNode;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.Set;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/** Utility class to generate Graphviz DOT representations of Agent structures. */\npublic class AgentGraphGenerator {\n\n private static final Logger log = LoggerFactory.getLogger(AgentGraphGenerator.class);\n\n private static final Color DARK_GREEN = Color.rgb(\"#0F5223\");\n private static final Color LIGHT_GREEN = Color.rgb(\"#69CB87\");\n private static final Color LIGHT_GRAY = Color.rgb(\"#CCCCCC\");\n private static final Color BG_COLOR = Color.rgb(\"#333537\");\n\n /**\n * Generates the DOT source string for the agent graph.\n *\n * @param rootAgent The root agent of the structure.\n * @param highlightPairs A list where each inner list contains two strings (fromNode, toNode)\n * representing an edge to highlight. Order matters for direction.\n * @return The DOT source string, or null if graph generation fails.\n */\n public static Optional getAgentGraphDotSource(\n BaseAgent rootAgent, List> highlightPairs) {\n log.debug(\n \"Building agent graph with root: {}, highlights: {}\", rootAgent.name(), highlightPairs);\n try {\n MutableGraph graph =\n Factory.mutGraph(\"AgentGraph\")\n .setDirected(true)\n .graphAttrs()\n .add(Rank.dir(Rank.RankDir.LEFT_TO_RIGHT), BG_COLOR.background());\n\n Set visitedNodes = new HashSet<>();\n buildGraphRecursive(graph, rootAgent, highlightPairs, visitedNodes);\n\n String dotSource = Graphviz.fromGraph(graph).render(Format.DOT).toString();\n log.debug(\"Generated DOT source successfully.\");\n return Optional.of(dotSource);\n } catch (Exception e) {\n log.error(\"Error generating agent graph DOT source\", e);\n return Optional.empty();\n }\n }\n\n /** Recursively builds the graph structure. */\n private static void buildGraphRecursive(\n MutableGraph graph,\n BaseAgent agent,\n List> highlightPairs,\n Set visitedNodes) {\n if (agent == null || visitedNodes.contains(getNodeName(agent))) {\n return;\n }\n\n drawNode(graph, agent, highlightPairs, visitedNodes);\n\n if (agent.subAgents() != null) {\n for (BaseAgent subAgent : agent.subAgents()) {\n if (subAgent != null) {\n drawEdge(graph, getNodeName(agent), getNodeName(subAgent), highlightPairs);\n buildGraphRecursive(graph, subAgent, highlightPairs, visitedNodes);\n }\n }\n }\n\n if (agent instanceof LlmAgent) {\n LlmAgent llmAgent = (LlmAgent) agent;\n List tools = llmAgent.canonicalTools().toList().blockingGet();\n if (tools != null) {\n for (BaseTool tool : tools) {\n if (tool != null) {\n drawNode(graph, tool, highlightPairs, visitedNodes);\n drawEdge(graph, getNodeName(agent), getNodeName(tool), highlightPairs);\n }\n }\n }\n }\n }\n\n /** Draws a node for an agent or tool, applying highlighting if applicable. */\n private static void drawNode(\n MutableGraph graph,\n Object toolOrAgent,\n List> highlightPairs,\n Set visitedNodes) {\n String name = getNodeName(toolOrAgent);\n if (name == null || name.isEmpty() || visitedNodes.contains(name)) {\n return;\n }\n\n Shape shape = getNodeShape(toolOrAgent);\n String caption = getNodeCaption(toolOrAgent);\n boolean isHighlighted = isNodeHighlighted(name, highlightPairs);\n\n MutableNode node =\n Factory.mutNode(name).add(Label.of(caption)).add(shape).add(LIGHT_GRAY.font());\n if (isHighlighted) {\n node.add(Style.FILLED);\n node.add(DARK_GREEN);\n } else {\n node.add(Style.ROUNDED);\n node.add(LIGHT_GRAY);\n }\n graph.add(node);\n visitedNodes.add(name);\n log.trace(\n \"Added node: name={}, caption={}, shape={}, highlighted={}\",\n name,\n caption,\n shape,\n isHighlighted);\n }\n\n /** Draws an edge between two nodes, applying highlighting if applicable. */\n private static void drawEdge(\n MutableGraph graph, String fromName, String toName, List> highlightPairs) {\n if (fromName == null || fromName.isEmpty() || toName == null || toName.isEmpty()) {\n log.warn(\n \"Skipping edge draw due to null or empty name: from='{}', to='{}'\", fromName, toName);\n return;\n }\n\n Optional highlightForward = isEdgeHighlighted(fromName, toName, highlightPairs);\n Link link = Factory.to(Factory.mutNode(toName));\n\n if (highlightForward.isPresent()) {\n link = link.with(LIGHT_GREEN);\n if (!highlightForward.get()) { // If true, means b->a was highlighted, draw reverse arrow\n link = link.with(Arrow.NORMAL.dir(Arrow.DirType.BACK));\n } else {\n link = link.with(Arrow.NORMAL);\n }\n } else {\n link = link.with(LIGHT_GRAY, Arrow.NONE);\n }\n\n graph.add(Factory.mutNode(fromName).addLink(link));\n log.trace(\n \"Added edge: from={}, to={}, highlighted={}\",\n fromName,\n toName,\n highlightForward.isPresent());\n }\n\n private static String getNodeName(Object toolOrAgent) {\n if (toolOrAgent instanceof BaseAgent) {\n return ((BaseAgent) toolOrAgent).name();\n } else if (toolOrAgent instanceof BaseTool) {\n return ((BaseTool) toolOrAgent).name();\n } else {\n log.warn(\"Unsupported type for getNodeName: {}\", toolOrAgent.getClass().getName());\n return \"unknown_\" + toolOrAgent.hashCode();\n }\n }\n\n private static String getNodeCaption(Object toolOrAgent) {\n String name = getNodeName(toolOrAgent); // Get name first\n if (toolOrAgent instanceof BaseAgent) {\n return \"🤖 \" + name;\n } else if (toolOrAgent instanceof BaseRetrievalTool) {\n return \"🔎 \" + name;\n } else if (toolOrAgent instanceof FunctionTool) {\n return \"🔧 \" + name;\n } else if (toolOrAgent instanceof AgentTool) {\n return \"🤖 \" + name;\n } else if (toolOrAgent instanceof BaseTool) {\n return \"🔧 \" + name;\n } else {\n log.warn(\"Unsupported type for getNodeCaption: {}\", toolOrAgent.getClass().getName());\n return \"❓ \" + name;\n }\n }\n\n private static Shape getNodeShape(Object toolOrAgent) {\n if (toolOrAgent instanceof BaseAgent) {\n return Shape.ELLIPSE;\n } else if (toolOrAgent instanceof BaseRetrievalTool) {\n return Shape.CYLINDER;\n } else if (toolOrAgent instanceof FunctionTool) {\n return Shape.BOX;\n } else if (toolOrAgent instanceof BaseTool) {\n return Shape.BOX;\n } else {\n log.warn(\"Unsupported type for getNodeShape: {}\", toolOrAgent.getClass().getName());\n return Shape.EGG;\n }\n }\n\n private static boolean isNodeHighlighted(String nodeName, List> highlightPairs) {\n if (highlightPairs == null || nodeName == null) {\n return false;\n }\n for (List pair : highlightPairs) {\n if (pair != null && pair.contains(nodeName)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Checks if an edge should be highlighted. Returns Optional: empty=no, true=forward,\n * false=backward\n */\n private static Optional isEdgeHighlighted(\n String fromName, String toName, List> highlightPairs) {\n if (highlightPairs == null || fromName == null || toName == null) {\n return Optional.empty();\n }\n for (List pair : highlightPairs) {\n if (pair != null && pair.size() == 2) {\n String pairFrom = pair.get(0);\n String pairTo = pair.get(1);\n if (fromName.equals(pairFrom) && toName.equals(pairTo)) {\n return Optional.of(true);\n }\n if (fromName.equals(pairTo) && toName.equals(pairFrom)) {\n return Optional.of(false);\n }\n }\n }\n return Optional.empty();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/agents/ReadonlyContext.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.agents;\n\nimport com.google.adk.events.Event;\nimport com.google.genai.types.Content;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\n\n/** Provides read-only access to the context of an agent run. */\npublic class ReadonlyContext {\n\n protected final InvocationContext invocationContext;\n private List eventsView;\n private Map stateView;\n\n public ReadonlyContext(InvocationContext invocationContext) {\n this.invocationContext = invocationContext;\n }\n\n /** Returns the user content that initiated this invocation. */\n public Optional userContent() {\n return invocationContext.userContent();\n }\n\n /** Returns the ID of the current invocation. */\n public String invocationId() {\n return invocationContext.invocationId();\n }\n\n /** Returns the branch of the current invocation, if present. */\n public Optional branch() {\n return invocationContext.branch();\n }\n\n /** Returns the name of the agent currently running. */\n public String agentName() {\n return invocationContext.agent().name();\n }\n\n /** Returns the session ID. */\n public String sessionId() {\n return invocationContext.session().id();\n }\n\n /**\n * Returns an unmodifiable view of the events of the session.\n *\n *

Warning: This is a live view, not a snapshot.\n */\n public List events() {\n if (eventsView == null) {\n eventsView = Collections.unmodifiableList(invocationContext.session().events());\n }\n return eventsView;\n }\n\n /**\n * Returns an unmodifiable view of the state of the session.\n *\n *

Warning: This is a live view, not a snapshot.\n */\n public Map state() {\n if (stateView == null) {\n stateView = Collections.unmodifiableMap(invocationContext.session().state());\n }\n return stateView;\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/llmflows/Instructions.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows.llmflows;\n\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.agents.LlmAgent;\nimport com.google.adk.agents.ReadonlyContext;\nimport com.google.adk.models.LlmRequest;\nimport com.google.adk.utils.InstructionUtils;\nimport com.google.common.collect.ImmutableList;\nimport io.reactivex.rxjava3.core.Single;\n\n/** {@link RequestProcessor} that handles instructions and global instructions for LLM flows. */\npublic final class Instructions implements RequestProcessor {\n public Instructions() {}\n\n @Override\n public Single processRequest(\n InvocationContext context, LlmRequest request) {\n if (!(context.agent() instanceof LlmAgent)) {\n return Single.error(\n new IllegalArgumentException(\n \"Agent in InvocationContext is not an instance of LlmAgent.\"));\n }\n LlmAgent agent = (LlmAgent) context.agent();\n ReadonlyContext readonlyContext = new ReadonlyContext(context);\n Single builderSingle = Single.just(request.toBuilder());\n if (agent.rootAgent() instanceof LlmAgent) {\n LlmAgent rootAgent = (LlmAgent) agent.rootAgent();\n builderSingle =\n builderSingle.flatMap(\n builder ->\n rootAgent\n .canonicalGlobalInstruction(readonlyContext)\n .flatMap(\n globalInstr -> {\n if (!globalInstr.isEmpty()) {\n return InstructionUtils.injectSessionState(context, globalInstr)\n .map(\n resolvedGlobalInstr ->\n builder.appendInstructions(\n ImmutableList.of(resolvedGlobalInstr)));\n }\n return Single.just(builder);\n }));\n }\n\n builderSingle =\n builderSingle.flatMap(\n builder ->\n agent\n .canonicalInstruction(readonlyContext)\n .flatMap(\n agentInstr -> {\n if (!agentInstr.isEmpty()) {\n return InstructionUtils.injectSessionState(context, agentInstr)\n .map(\n resolvedAgentInstr ->\n builder.appendInstructions(\n ImmutableList.of(resolvedAgentInstr)));\n }\n return Single.just(builder);\n }));\n\n return builderSingle.map(\n finalBuilder ->\n RequestProcessor.RequestProcessingResult.create(\n finalBuilder.build(), ImmutableList.of()));\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/mcp/McpSessionManager.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools.mcp;\n\nimport io.modelcontextprotocol.client.McpClient;\nimport io.modelcontextprotocol.client.McpSyncClient;\nimport io.modelcontextprotocol.spec.McpClientTransport;\nimport io.modelcontextprotocol.spec.McpSchema.ClientCapabilities;\nimport io.modelcontextprotocol.spec.McpSchema.InitializeResult;\nimport java.time.Duration;\nimport java.util.Optional;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/**\n * Manages MCP client sessions.\n *\n *

This class provides methods for creating and initializing MCP client sessions, handling\n * different connection parameters and transport builders.\n */\n// TODO(b/413489523): Implement this class.\npublic class McpSessionManager {\n\n private final Object connectionParams; // ServerParameters or SseServerParameters\n private static final Logger logger = LoggerFactory.getLogger(McpSessionManager.class);\n\n public McpSessionManager(Object connectionParams) {\n this.connectionParams = connectionParams;\n }\n\n public McpSyncClient createSession() {\n return initializeSession(this.connectionParams);\n }\n\n public static McpSyncClient initializeSession(Object connectionParams) {\n return initializeSession(connectionParams, new DefaultMcpTransportBuilder());\n }\n\n public static McpSyncClient initializeSession(\n Object connectionParams, McpTransportBuilder transportBuilder) {\n Duration initializationTimeout = null;\n Duration requestTimeout = null;\n McpClientTransport transport = transportBuilder.build(connectionParams);\n if (connectionParams instanceof SseServerParameters sseServerParams) {\n initializationTimeout = sseServerParams.timeout();\n requestTimeout = sseServerParams.sseReadTimeout();\n }\n McpSyncClient client =\n McpClient.sync(transport)\n .initializationTimeout(\n Optional.ofNullable(initializationTimeout).orElse(Duration.ofSeconds(10)))\n .requestTimeout(Optional.ofNullable(requestTimeout).orElse(Duration.ofSeconds(10)))\n .capabilities(ClientCapabilities.builder().build())\n .build();\n InitializeResult initResult = client.initialize();\n logger.debug(\"Initialize Client Result: {}\", initResult);\n return client;\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/applicationintegrationtoolset/ApplicationIntegrationToolset.java", "package com.google.adk.tools.applicationintegrationtoolset;\n\nimport static com.google.common.base.Strings.isNullOrEmpty;\n\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.fasterxml.jackson.databind.node.ObjectNode;\nimport com.google.adk.agents.ReadonlyContext;\nimport com.google.adk.tools.BaseTool;\nimport com.google.adk.tools.BaseToolset;\nimport com.google.adk.tools.applicationintegrationtoolset.IntegrationConnectorTool.DefaultHttpExecutor;\nimport com.google.adk.tools.applicationintegrationtoolset.IntegrationConnectorTool.HttpExecutor;\nimport io.reactivex.rxjava3.core.Flowable;\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport org.jspecify.annotations.Nullable;\n\n/** Application Integration Toolset */\npublic class ApplicationIntegrationToolset implements BaseToolset {\n String project;\n String location;\n @Nullable String integration;\n @Nullable List triggers;\n @Nullable String connection;\n @Nullable Map> entityOperations;\n @Nullable List actions;\n String serviceAccountJson;\n @Nullable String toolNamePrefix;\n @Nullable String toolInstructions;\n public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();\n HttpExecutor httpExecutor;\n\n /**\n * ApplicationIntegrationToolset generates tools from a given Application Integration resource.\n *\n *

Example Usage:\n *\n *

integrationTool = new ApplicationIntegrationToolset( project=\"test-project\",\n * location=\"us-central1\", integration=\"test-integration\",\n * triggers=ImmutableList.of(\"api_trigger/test_trigger\", \"api_trigger/test_trigger_2\",\n * serviceAccountJson=\"{....}\"),connection=null,enitityOperations=null,actions=null,toolNamePrefix=\"test-integration-tool\",toolInstructions=\"This\n * tool is used to get response from test-integration.\");\n *\n *

connectionTool = new ApplicationIntegrationToolset( project=\"test-project\",\n * location=\"us-central1\", integration=null, triggers=null, connection=\"test-connection\",\n * entityOperations=ImmutableMap.of(\"Entity1\", ImmutableList.of(\"LIST\", \"GET\", \"UPDATE\")),\n * \"Entity2\", ImmutableList.of()), actions=ImmutableList.of(\"ExecuteCustomQuery\"),\n * serviceAccountJson=\"{....}\", toolNamePrefix=\"test-tool\", toolInstructions=\"This tool is used to\n * list, get and update issues in Jira.\");\n *\n * @param project The GCP project ID.\n * @param location The GCP location of integration.\n * @param integration The integration name.\n * @param triggers(Optional) The list of trigger ids in the integration.\n * @param connection(Optional) The connection name.\n * @param entityOperations(Optional) The entity operations.\n * @param actions(Optional) The actions.\n * @param serviceAccountJson(Optional) The service account configuration as a dictionary. Required\n * if not using default service credential. Used for fetching the Application Integration or\n * Integration Connector resource.\n * @param toolNamePrefix(Optional) The tool name prefix.\n * @param toolInstructions(Optional) The tool instructions.\n */\n public ApplicationIntegrationToolset(\n String project,\n String location,\n String integration,\n List triggers,\n String connection,\n Map> entityOperations,\n List actions,\n String serviceAccountJson,\n String toolNamePrefix,\n String toolInstructions) {\n this(\n project,\n location,\n integration,\n triggers,\n connection,\n entityOperations,\n actions,\n serviceAccountJson,\n toolNamePrefix,\n toolInstructions,\n new DefaultHttpExecutor().createExecutor(serviceAccountJson));\n }\n\n ApplicationIntegrationToolset(\n String project,\n String location,\n String integration,\n List triggers,\n String connection,\n Map> entityOperations,\n List actions,\n String serviceAccountJson,\n String toolNamePrefix,\n String toolInstructions,\n HttpExecutor httpExecutor) {\n this.project = project;\n this.location = location;\n this.integration = integration;\n this.triggers = triggers;\n this.connection = connection;\n this.entityOperations = entityOperations;\n this.actions = actions;\n this.serviceAccountJson = serviceAccountJson;\n this.toolNamePrefix = toolNamePrefix;\n this.toolInstructions = toolInstructions;\n this.httpExecutor = httpExecutor;\n }\n\n List getPathUrl(String openApiSchemaString) throws Exception {\n List pathUrls = new ArrayList<>();\n JsonNode topLevelNode = OBJECT_MAPPER.readTree(openApiSchemaString);\n JsonNode specNode = topLevelNode.path(\"openApiSpec\");\n if (specNode.isMissingNode() || !specNode.isTextual()) {\n throw new IllegalArgumentException(\n \"Failed to get OpenApiSpec, please check the project and region for the integration.\");\n }\n JsonNode rootNode = OBJECT_MAPPER.readTree(specNode.asText());\n JsonNode pathsNode = rootNode.path(\"paths\");\n Iterator> paths = pathsNode.fields();\n while (paths.hasNext()) {\n Map.Entry pathEntry = paths.next();\n String pathUrl = pathEntry.getKey();\n pathUrls.add(pathUrl);\n }\n return pathUrls;\n }\n\n private List getAllTools() throws Exception {\n String openApiSchemaString = null;\n List tools = new ArrayList<>();\n if (!isNullOrEmpty(this.integration)) {\n IntegrationClient integrationClient =\n new IntegrationClient(\n this.project,\n this.location,\n this.integration,\n this.triggers,\n null,\n null,\n null,\n this.httpExecutor);\n openApiSchemaString = integrationClient.generateOpenApiSpec();\n List pathUrls = getPathUrl(openApiSchemaString);\n for (String pathUrl : pathUrls) {\n String toolName = integrationClient.getOperationIdFromPathUrl(openApiSchemaString, pathUrl);\n if (toolName != null) {\n tools.add(\n new IntegrationConnectorTool(\n openApiSchemaString,\n pathUrl,\n toolName,\n toolInstructions,\n null,\n null,\n null,\n this.serviceAccountJson,\n this.httpExecutor));\n }\n }\n } else if (!isNullOrEmpty(this.connection)\n && (this.entityOperations != null || this.actions != null)) {\n IntegrationClient integrationClient =\n new IntegrationClient(\n this.project,\n this.location,\n null,\n null,\n this.connection,\n this.entityOperations,\n this.actions,\n this.httpExecutor);\n ObjectNode parentOpenApiSpec = OBJECT_MAPPER.createObjectNode();\n ObjectNode openApiSpec =\n integrationClient.getOpenApiSpecForConnection(toolNamePrefix, toolInstructions);\n String openApiSpecString = OBJECT_MAPPER.writeValueAsString(openApiSpec);\n parentOpenApiSpec.put(\"openApiSpec\", openApiSpecString);\n openApiSchemaString = OBJECT_MAPPER.writeValueAsString(parentOpenApiSpec);\n List pathUrls = getPathUrl(openApiSchemaString);\n for (String pathUrl : pathUrls) {\n String toolName = integrationClient.getOperationIdFromPathUrl(openApiSchemaString, pathUrl);\n if (!isNullOrEmpty(toolName)) {\n ConnectionsClient connectionsClient =\n new ConnectionsClient(\n this.project, this.location, this.connection, this.httpExecutor, OBJECT_MAPPER);\n ConnectionsClient.ConnectionDetails connectionDetails =\n connectionsClient.getConnectionDetails();\n\n tools.add(\n new IntegrationConnectorTool(\n openApiSchemaString,\n pathUrl,\n toolName,\n \"\",\n connectionDetails.name,\n connectionDetails.serviceName,\n connectionDetails.host,\n this.serviceAccountJson,\n this.httpExecutor));\n }\n }\n } else {\n throw new IllegalArgumentException(\n \"Invalid request, Either integration or (connection and\"\n + \" (entityOperations or actions)) should be provided.\");\n }\n\n return tools;\n }\n\n @Override\n public Flowable getTools(@Nullable ReadonlyContext readonlyContext) {\n try {\n List allTools = getAllTools();\n return Flowable.fromIterable(allTools);\n } catch (Exception e) {\n return Flowable.error(e);\n }\n }\n\n @Override\n public void close() throws Exception {\n // Nothing to close.\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/sessions/HttpApiClient.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\nimport com.google.auth.oauth2.GoogleCredentials;\nimport com.google.common.base.Ascii;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.genai.errors.GenAiIOException;\nimport com.google.genai.types.HttpOptions;\nimport java.io.IOException;\nimport java.util.Map;\nimport java.util.Optional;\nimport okhttp3.MediaType;\nimport okhttp3.Request;\nimport okhttp3.RequestBody;\nimport okhttp3.Response;\n\n/** Base client for the HTTP APIs. */\npublic class HttpApiClient extends ApiClient {\n public static final MediaType MEDIA_TYPE_APPLICATION_JSON =\n MediaType.parse(\"application/json; charset=utf-8\");\n\n /** Constructs an ApiClient for Google AI APIs. */\n HttpApiClient(Optional apiKey, Optional httpOptions) {\n super(apiKey, httpOptions);\n }\n\n /** Constructs an ApiClient for Vertex AI APIs. */\n HttpApiClient(\n Optional project,\n Optional location,\n Optional credentials,\n Optional httpOptions) {\n super(project, location, credentials, httpOptions);\n }\n\n /** Sends a Http request given the http method, path, and request json string. */\n @Override\n public ApiResponse request(String httpMethod, String path, String requestJson) {\n boolean queryBaseModel =\n Ascii.equalsIgnoreCase(httpMethod, \"GET\") && path.startsWith(\"publishers/google/models/\");\n if (this.vertexAI() && !path.startsWith(\"projects/\") && !queryBaseModel) {\n path =\n String.format(\"projects/%s/locations/%s/\", this.project.get(), this.location.get())\n + path;\n }\n String requestUrl =\n String.format(\n \"%s/%s/%s\", httpOptions.baseUrl().get(), httpOptions.apiVersion().get(), path);\n\n Request.Builder requestBuilder = new Request.Builder().url(requestUrl);\n setHeaders(requestBuilder);\n\n if (Ascii.equalsIgnoreCase(httpMethod, \"POST\")) {\n requestBuilder.post(RequestBody.create(MEDIA_TYPE_APPLICATION_JSON, requestJson));\n\n } else if (Ascii.equalsIgnoreCase(httpMethod, \"GET\")) {\n requestBuilder.get();\n } else if (Ascii.equalsIgnoreCase(httpMethod, \"DELETE\")) {\n requestBuilder.delete();\n } else {\n throw new IllegalArgumentException(\"Unsupported HTTP method: \" + httpMethod);\n }\n return executeRequest(requestBuilder.build());\n }\n\n /** Sets the required headers (including auth) on the request object. */\n private void setHeaders(Request.Builder requestBuilder) {\n for (Map.Entry header :\n httpOptions.headers().orElse(ImmutableMap.of()).entrySet()) {\n requestBuilder.header(header.getKey(), header.getValue());\n }\n\n if (apiKey.isPresent()) {\n requestBuilder.header(\"x-goog-api-key\", apiKey.get());\n } else {\n GoogleCredentials cred =\n credentials.orElseThrow(() -> new IllegalStateException(\"credentials is required\"));\n try {\n cred.refreshIfExpired();\n } catch (IOException e) {\n throw new GenAiIOException(\"Failed to refresh credentials.\", e);\n }\n String accessToken;\n try {\n accessToken = cred.getAccessToken().getTokenValue();\n } catch (NullPointerException e) {\n // For test cases where the access token is not available.\n if (e.getMessage()\n .contains(\n \"because the return value of\"\n + \" \\\"com.google.auth.oauth2.GoogleCredentials.getAccessToken()\\\" is null\")) {\n accessToken = \"\";\n } else {\n throw e;\n }\n }\n requestBuilder.header(\"Authorization\", \"Bearer \" + accessToken);\n\n if (cred.getQuotaProjectId() != null) {\n requestBuilder.header(\"x-goog-user-project\", cred.getQuotaProjectId());\n }\n }\n }\n\n /** Executes the given HTTP request. */\n private ApiResponse executeRequest(Request request) {\n try {\n Response response = httpClient.newCall(request).execute();\n return new HttpApiResponse(response);\n } catch (IOException e) {\n throw new GenAiIOException(\"Failed to execute HTTP request.\", e);\n }\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/llmflows/AgentTransfer.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows.llmflows;\n\nimport com.google.adk.agents.BaseAgent;\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.agents.LlmAgent;\nimport com.google.adk.events.EventActions;\nimport com.google.adk.models.LlmRequest;\nimport com.google.adk.tools.FunctionTool;\nimport com.google.adk.tools.ToolContext;\nimport com.google.common.collect.ImmutableList;\nimport io.reactivex.rxjava3.core.Single;\nimport java.lang.reflect.Method;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/** {@link RequestProcessor} that handles agent transfer for LLM flow. */\npublic final class AgentTransfer implements RequestProcessor {\n\n public AgentTransfer() {}\n\n @Override\n public Single processRequest(\n InvocationContext context, LlmRequest request) {\n BaseAgent baseAgent = context.agent();\n if (!(baseAgent instanceof LlmAgent agent)) {\n throw new IllegalArgumentException(\n \"Base agent in InvocationContext is not an instance of Agent.\");\n }\n\n List transferTargets = getTransferTargets(agent);\n if (transferTargets.isEmpty()) {\n return Single.just(\n RequestProcessor.RequestProcessingResult.create(request, ImmutableList.of()));\n }\n\n LlmRequest.Builder builder =\n request.toBuilder()\n .appendInstructions(\n ImmutableList.of(buildTargetAgentsInstructions(agent, transferTargets)));\n Method transferToAgentMethod;\n try {\n transferToAgentMethod =\n AgentTransfer.class.getMethod(\"transferToAgent\", String.class, ToolContext.class);\n } catch (NoSuchMethodException e) {\n throw new IllegalStateException(e);\n }\n FunctionTool agentTransferTool = FunctionTool.create(transferToAgentMethod);\n agentTransferTool.processLlmRequest(builder, ToolContext.builder(context).build());\n return Single.just(\n RequestProcessor.RequestProcessingResult.create(builder.build(), ImmutableList.of()));\n }\n\n /** Builds a string with the target agent’s name and description. */\n private String buildTargetAgentsInfo(BaseAgent targetAgent) {\n return String.format(\n \"Agent name: %s\\nAgent description: %s\", targetAgent.name(), targetAgent.description());\n }\n\n /** Builds LLM instructions about when and how to transfer to another agent. */\n private String buildTargetAgentsInstructions(LlmAgent agent, List transferTargets) {\n StringBuilder sb = new StringBuilder();\n sb.append(\"You have a list of other agents to transfer to:\\n\");\n for (BaseAgent targetAgent : transferTargets) {\n sb.append(buildTargetAgentsInfo(targetAgent));\n sb.append(\"\\n\");\n }\n sb.append(\n \"If you are the best to answer the question according to your description, you can answer\"\n + \" it.\\n\");\n sb.append(\n \"If another agent is better for answering the question according to its description, call\"\n + \" `transferToAgent` function to transfer the question to that agent. When\"\n + \" transferring, do not generate any text other than the function call.\\n\");\n if (agent.parentAgent() != null) {\n sb.append(\"Your parent agent is \");\n sb.append(agent.parentAgent().name());\n sb.append(\n \".If neither the other agents nor you are best for answering the question according to\"\n + \" the descriptions, transfer to your parent agent. If you don't have parent agent,\"\n + \" try answer by yourself.\\n\");\n }\n return sb.toString();\n }\n\n /** Returns valid transfer targets: sub-agents, parent, and peers (if allowed). */\n private List getTransferTargets(LlmAgent agent) {\n List transferTargets = new ArrayList<>();\n transferTargets.addAll(agent.subAgents()); // Add all sub-agents\n\n BaseAgent parent = agent.parentAgent();\n // Agents eligible to transfer must have an LLM-based agent parent.\n if (!(parent instanceof LlmAgent)) {\n return transferTargets;\n }\n\n if (!agent.disallowTransferToParent()) {\n transferTargets.add(parent);\n }\n\n if (!agent.disallowTransferToPeers()) {\n for (BaseAgent peerAgent : parent.subAgents()) {\n if (!peerAgent.name().equals(agent.name())) {\n transferTargets.add(peerAgent);\n }\n }\n }\n\n return transferTargets;\n }\n\n /** Marks the target agent for transfer using the tool context. */\n public static void transferToAgent(String agentName, ToolContext toolContext) {\n EventActions eventActions = toolContext.eventActions();\n toolContext.setActions(eventActions.toBuilder().transferToAgent(agentName).build());\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/memory/BaseMemoryService.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.memory;\n\nimport com.google.adk.sessions.Session;\nimport io.reactivex.rxjava3.core.Completable;\nimport io.reactivex.rxjava3.core.Single;\n\n/**\n * Base contract for memory services.\n *\n *

The service provides functionalities to ingest sessions into memory so that the memory can be\n * used for user queries.\n */\npublic interface BaseMemoryService {\n\n /**\n * Adds a session to the memory service.\n *\n *

A session may be added multiple times during its lifetime.\n *\n * @param session The session to add.\n */\n Completable addSessionToMemory(Session session);\n\n /**\n * Searches for sessions that match the query asynchronously.\n *\n * @param appName The name of the application.\n * @param userId The id of the user.\n * @param query The query to search for.\n * @return A {@link SearchMemoryResponse} containing the matching memories.\n */\n Single searchMemory(String appName, String userId, String query);\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/GoogleSearchTool.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools;\n\nimport com.google.adk.models.LlmRequest;\nimport com.google.common.collect.ImmutableList;\nimport com.google.genai.types.GenerateContentConfig;\nimport com.google.genai.types.GoogleSearch;\nimport com.google.genai.types.GoogleSearchRetrieval;\nimport com.google.genai.types.Tool;\nimport io.reactivex.rxjava3.core.Completable;\nimport java.util.List;\n\n/**\n * A built-in tool that is automatically invoked by Gemini 2 models to retrieve search results from\n * Google Search.\n *\n *

This tool operates internally within the model and does not require or perform local code\n * execution.\n */\npublic final class GoogleSearchTool extends BaseTool {\n\n public GoogleSearchTool() {\n super(\"google_search\", \"google_search\");\n }\n\n @Override\n public Completable processLlmRequest(\n LlmRequest.Builder llmRequestBuilder, ToolContext toolContext) {\n\n GenerateContentConfig.Builder configBuilder =\n llmRequestBuilder\n .build()\n .config()\n .map(GenerateContentConfig::toBuilder)\n .orElse(GenerateContentConfig.builder());\n\n List existingTools = configBuilder.build().tools().orElse(ImmutableList.of());\n ImmutableList.Builder updatedToolsBuilder = ImmutableList.builder();\n updatedToolsBuilder.addAll(existingTools);\n\n String model = llmRequestBuilder.build().model().get();\n if (model != null && model.startsWith(\"gemini-1\")) {\n if (!updatedToolsBuilder.build().isEmpty()) {\n System.out.println(configBuilder.build().tools().get());\n return Completable.error(\n new IllegalArgumentException(\n \"Google search tool cannot be used with other tools in Gemini 1.x.\"));\n }\n updatedToolsBuilder.add(\n Tool.builder().googleSearchRetrieval(GoogleSearchRetrieval.builder().build()).build());\n configBuilder.tools(updatedToolsBuilder.build());\n } else if (model != null && model.startsWith(\"gemini-2\")) {\n\n updatedToolsBuilder.add(Tool.builder().googleSearch(GoogleSearch.builder().build()).build());\n configBuilder.tools(updatedToolsBuilder.build());\n } else {\n return Completable.error(\n new IllegalArgumentException(\"Google search tool is not supported for model \" + model));\n }\n\n llmRequestBuilder.config(configBuilder.build());\n return Completable.complete();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/agents/LoopAgent.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.agents;\n\nimport com.google.adk.events.Event;\nimport com.google.common.collect.ImmutableList;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport io.reactivex.rxjava3.core.Flowable;\nimport java.util.List;\nimport java.util.Optional;\n\n/**\n * An agent that runs its sub-agents sequentially in a loop.\n *\n *

The loop continues until a sub-agent escalates, or until the maximum number of iterations is\n * reached (if specified).\n */\npublic class LoopAgent extends BaseAgent {\n\n private final Optional maxIterations;\n\n /**\n * Constructor for LoopAgent.\n *\n * @param name The agent's name.\n * @param description The agent's description.\n * @param subAgents The list of sub-agents to run in the loop.\n * @param maxIterations Optional termination condition: maximum number of loop iterations.\n * @param beforeAgentCallback Optional callback before the agent runs.\n * @param afterAgentCallback Optional callback after the agent runs.\n */\n private LoopAgent(\n String name,\n String description,\n List subAgents,\n Optional maxIterations,\n List beforeAgentCallback,\n List afterAgentCallback) {\n\n super(name, description, subAgents, beforeAgentCallback, afterAgentCallback);\n this.maxIterations = maxIterations;\n }\n\n /** Builder for {@link LoopAgent}. */\n public static class Builder {\n private String name;\n private String description;\n private List subAgents;\n private Optional maxIterations = Optional.empty();\n private ImmutableList beforeAgentCallback;\n private ImmutableList afterAgentCallback;\n\n @CanIgnoreReturnValue\n public Builder name(String name) {\n this.name = name;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder description(String description) {\n this.description = description;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder subAgents(List subAgents) {\n this.subAgents = subAgents;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder subAgents(BaseAgent... subAgents) {\n this.subAgents = ImmutableList.copyOf(subAgents);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder maxIterations(int maxIterations) {\n this.maxIterations = Optional.of(maxIterations);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder maxIterations(Optional maxIterations) {\n this.maxIterations = maxIterations;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeAgentCallback(Callbacks.BeforeAgentCallback beforeAgentCallback) {\n this.beforeAgentCallback = ImmutableList.of(beforeAgentCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeAgentCallback(\n List beforeAgentCallback) {\n this.beforeAgentCallback = CallbackUtil.getBeforeAgentCallbacks(beforeAgentCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterAgentCallback(Callbacks.AfterAgentCallback afterAgentCallback) {\n this.afterAgentCallback = ImmutableList.of(afterAgentCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterAgentCallback(List afterAgentCallback) {\n this.afterAgentCallback = CallbackUtil.getAfterAgentCallbacks(afterAgentCallback);\n return this;\n }\n\n public LoopAgent build() {\n // TODO(b/410859954): Add validation for required fields like name.\n return new LoopAgent(\n name, description, subAgents, maxIterations, beforeAgentCallback, afterAgentCallback);\n }\n }\n\n public static Builder builder() {\n return new Builder();\n }\n\n @Override\n protected Flowable runAsyncImpl(InvocationContext invocationContext) {\n List subAgents = subAgents();\n if (subAgents == null || subAgents.isEmpty()) {\n return Flowable.empty();\n }\n\n return Flowable.fromIterable(subAgents)\n .concatMap(subAgent -> subAgent.runAsync(invocationContext))\n .repeat(maxIterations.orElse(Integer.MAX_VALUE))\n .takeUntil(LoopAgent::hasEscalateAction);\n }\n\n @Override\n protected Flowable runLiveImpl(InvocationContext invocationContext) {\n return Flowable.error(\n new UnsupportedOperationException(\"runLive is not defined for LoopAgent yet.\"));\n }\n\n private static boolean hasEscalateAction(Event event) {\n return event.actions().escalate().orElse(false);\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/models/LlmRegistry.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.models;\n\nimport java.util.Map;\nimport java.util.concurrent.ConcurrentHashMap;\n\n/** Central registry for managing Large Language Model (LLM) instances. */\npublic final class LlmRegistry {\n\n /** A thread-safe cache mapping model names to LLM instances. */\n private static final Map instances = new ConcurrentHashMap<>();\n\n /** The factory interface for creating LLM instances. */\n @FunctionalInterface\n public interface LlmFactory {\n BaseLlm create(String modelName);\n }\n\n /** Map of model name patterns regex to factories. */\n private static final Map llmFactories = new ConcurrentHashMap<>();\n\n /** Registers default LLM factories, e.g. for Gemini models. */\n static {\n registerLlm(\"gemini-.*\", modelName -> Gemini.builder().modelName(modelName).build());\n }\n\n /**\n * Registers a factory for model names matching the given regex pattern.\n *\n * @param modelNamePattern Regex pattern for matching model names.\n * @param factory Factory to create LLM instances.\n */\n public static void registerLlm(String modelNamePattern, LlmFactory factory) {\n llmFactories.put(modelNamePattern, factory);\n }\n\n /**\n * Returns an LLM instance for the given model name, using a cached or new factory-created\n * instance.\n *\n * @param modelName Model name to look up.\n * @return Matching {@link BaseLlm} instance.\n * @throws IllegalArgumentException If no factory matches the model name.\n */\n public static BaseLlm getLlm(String modelName) {\n return instances.computeIfAbsent(modelName, LlmRegistry::createLlm);\n }\n\n /**\n * Creates a {@link BaseLlm} by matching the model name against registered factories.\n *\n * @param modelName Model name to match.\n * @return A new {@link BaseLlm} instance.\n * @throws IllegalArgumentException If no factory matches the model name.\n */\n private static BaseLlm createLlm(String modelName) {\n for (Map.Entry entry : llmFactories.entrySet()) {\n if (modelName.matches(entry.getKey())) {\n return entry.getValue().create(modelName);\n }\n }\n throw new IllegalArgumentException(\"Unsupported model: \" + modelName);\n }\n\n /**\n * Registers an LLM factory for testing purposes. Clears cached instances matching the given\n * pattern to ensure test isolation.\n *\n * @param modelNamePattern Regex pattern for matching model names.\n * @param factory The {@link LlmFactory} to register.\n */\n static void registerTestLlm(String modelNamePattern, LlmFactory factory) {\n llmFactories.put(modelNamePattern, factory);\n // Clear any cached instances that match this pattern to ensure test isolation.\n instances.keySet().removeIf(modelName -> modelName.matches(modelNamePattern));\n }\n\n private LlmRegistry() {}\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/models/LlmResponse.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.models;\n\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.databind.annotation.JsonDeserialize;\nimport com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;\nimport com.google.adk.JsonBaseModel;\nimport com.google.auto.value.AutoValue;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport com.google.genai.types.Candidate;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.FinishReason;\nimport com.google.genai.types.GenerateContentResponse;\nimport com.google.genai.types.GenerateContentResponsePromptFeedback;\nimport com.google.genai.types.GroundingMetadata;\nimport java.util.List;\nimport java.util.Optional;\nimport javax.annotation.Nullable;\n\n/** Represents a response received from the LLM. */\n@AutoValue\n@JsonDeserialize(builder = LlmResponse.Builder.class)\npublic abstract class LlmResponse extends JsonBaseModel {\n\n LlmResponse() {}\n\n /**\n * Returns the content of the first candidate in the response, if available.\n *\n * @return An {@link Content} of the first {@link Candidate} in the {@link\n * GenerateContentResponse} if the response contains at least one candidate., or an empty\n * optional if no candidates are present in the response.\n */\n @JsonProperty(\"content\")\n public abstract Optional content();\n\n /**\n * Returns the grounding metadata of the first candidate in the response, if available.\n *\n * @return An {@link Optional} containing {@link GroundingMetadata} or empty.\n */\n @JsonProperty(\"groundingMetadata\")\n public abstract Optional groundingMetadata();\n\n /**\n * Indicates whether the text content is part of a unfinished text stream.\n *\n *

Only used for streaming mode and when the content is plain text.\n */\n @JsonProperty(\"partial\")\n public abstract Optional partial();\n\n /**\n * Indicates whether the response from the model is complete.\n *\n *

Only used for streaming mode.\n */\n @JsonProperty(\"turnComplete\")\n public abstract Optional turnComplete();\n\n /** Error code if the response is an error. Code varies by model. */\n @JsonProperty(\"errorCode\")\n public abstract Optional errorCode();\n\n /** Error message if the response is an error. */\n @JsonProperty(\"errorMessage\")\n public abstract Optional errorMessage();\n\n /**\n * Indicates that LLM was interrupted when generating the content. Usually it's due to user\n * interruption during a bidi streaming.\n */\n @JsonProperty(\"interrupted\")\n public abstract Optional interrupted();\n\n public abstract Builder toBuilder();\n\n /** Builder for constructing {@link LlmResponse} instances. */\n @AutoValue.Builder\n @JsonPOJOBuilder(buildMethodName = \"build\", withPrefix = \"\")\n public abstract static class Builder {\n\n @JsonCreator\n static LlmResponse.Builder jacksonBuilder() {\n return LlmResponse.builder();\n }\n\n @JsonProperty(\"content\")\n public abstract Builder content(Content content);\n\n @JsonProperty(\"interrupted\")\n public abstract Builder interrupted(@Nullable Boolean interrupted);\n\n public abstract Builder interrupted(Optional interrupted);\n\n @JsonProperty(\"groundingMetadata\")\n public abstract Builder groundingMetadata(@Nullable GroundingMetadata groundingMetadata);\n\n public abstract Builder groundingMetadata(Optional groundingMetadata);\n\n @JsonProperty(\"partial\")\n public abstract Builder partial(@Nullable Boolean partial);\n\n public abstract Builder partial(Optional partial);\n\n @JsonProperty(\"turnComplete\")\n public abstract Builder turnComplete(@Nullable Boolean turnComplete);\n\n public abstract Builder turnComplete(Optional turnComplete);\n\n @JsonProperty(\"errorCode\")\n public abstract Builder errorCode(@Nullable FinishReason errorCode);\n\n public abstract Builder errorCode(Optional errorCode);\n\n @JsonProperty(\"errorMessage\")\n public abstract Builder errorMessage(@Nullable String errorMessage);\n\n public abstract Builder errorMessage(Optional errorMessage);\n\n @CanIgnoreReturnValue\n public final Builder response(GenerateContentResponse response) {\n Optional> candidatesOpt = response.candidates();\n if (candidatesOpt.isPresent() && !candidatesOpt.get().isEmpty()) {\n Candidate candidate = candidatesOpt.get().get(0);\n if (candidate.content().isPresent()) {\n this.content(candidate.content().get());\n this.groundingMetadata(candidate.groundingMetadata());\n } else {\n candidate.finishReason().ifPresent(this::errorCode);\n candidate.finishMessage().ifPresent(this::errorMessage);\n }\n } else {\n Optional promptFeedbackOpt =\n response.promptFeedback();\n if (promptFeedbackOpt.isPresent()) {\n GenerateContentResponsePromptFeedback promptFeedback = promptFeedbackOpt.get();\n promptFeedback\n .blockReason()\n .ifPresent(reason -> this.errorCode(new FinishReason(reason.toString())));\n promptFeedback.blockReasonMessage().ifPresent(this::errorMessage);\n } else {\n this.errorCode(new FinishReason(\"Unknown error.\"));\n this.errorMessage(\"Unknown error.\");\n }\n }\n return this;\n }\n\n abstract LlmResponse autoBuild();\n\n public LlmResponse build() {\n return autoBuild();\n }\n }\n\n public static Builder builder() {\n return new AutoValue_LlmResponse.Builder();\n }\n\n public static LlmResponse create(List candidates) {\n GenerateContentResponse response =\n GenerateContentResponse.builder().candidates(candidates).build();\n return builder().response(response).build();\n }\n\n public static LlmResponse create(GenerateContentResponse response) {\n return builder().response(response).build();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/SchemaUtils.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk;\n\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.google.genai.types.Schema;\nimport com.google.genai.types.Type;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\n/** Utility class for validating schemas. */\npublic final class SchemaUtils {\n\n private SchemaUtils() {} // Private constructor for utility class\n\n /**\n * Matches a value against a schema type.\n *\n * @param value The value to match.\n * @param schema The schema to match against.\n * @param isInput Whether the value is an input or output.\n * @return True if the value matches the schema type, false otherwise.\n * @throws IllegalArgumentException If the schema type is not supported.\n */\n @SuppressWarnings(\"unchecked\") // For tool parameter type casting.\n private static Boolean matchType(Object value, Schema schema, Boolean isInput) {\n // Based on types from https://cloud.google.com/vertex-ai/docs/reference/rest/v1/Schema\n Type.Known type = schema.type().get().knownEnum();\n switch (type) {\n case STRING:\n return value instanceof String;\n case INTEGER:\n return value instanceof Integer;\n case BOOLEAN:\n return value instanceof Boolean;\n case NUMBER:\n return value instanceof Number;\n case ARRAY:\n if (value instanceof List) {\n for (Object element : (List) value) {\n if (!matchType(element, schema.items().get(), isInput)) {\n return false;\n }\n }\n return true;\n }\n return false;\n case OBJECT:\n if (value instanceof Map) {\n validateMapOnSchema((Map) value, schema, isInput);\n return true;\n } else {\n return false;\n }\n case TYPE_UNSPECIFIED:\n throw new IllegalArgumentException(\n \"Unsupported type: \" + type + \" is not a Open API data type.\");\n default:\n // This category includes NULL, which is not supported.\n break;\n }\n return false;\n }\n\n /**\n * Validates a map against a schema.\n *\n * @param args The map to validate.\n * @param schema The schema to validate against.\n * @param isInput Whether the map is an input or output.\n * @throws IllegalArgumentException If the map does not match the schema.\n */\n public static void validateMapOnSchema(Map args, Schema schema, Boolean isInput) {\n Map properties = schema.properties().get();\n for (Entry arg : args.entrySet()) {\n // Check if the argument is in the schema.\n if (!properties.containsKey(arg.getKey())) {\n if (isInput) {\n throw new IllegalArgumentException(\n \"Input arg: \" + arg.getKey() + \" does not match agent input schema: \" + schema);\n } else {\n throw new IllegalArgumentException(\n \"Output arg: \" + arg.getKey() + \" does not match agent output schema: \" + schema);\n }\n }\n // Check if the argument type matches the schema type.\n if (!matchType(arg.getValue(), properties.get(arg.getKey()), isInput)) {\n if (isInput) {\n throw new IllegalArgumentException(\n \"Input arg: \" + arg.getKey() + \" does not match agent input schema: \" + schema);\n } else {\n throw new IllegalArgumentException(\n \"Output arg: \" + arg.getKey() + \" does not match agent output schema: \" + schema);\n }\n }\n }\n // Check if all required arguments are present.\n if (schema.required().isPresent()) {\n for (String required : schema.required().get()) {\n if (!args.containsKey(required)) {\n if (isInput) {\n throw new IllegalArgumentException(\"Input args does not contain required \" + required);\n } else {\n throw new IllegalArgumentException(\"Output args does not contain required \" + required);\n }\n }\n }\n }\n }\n\n /**\n * Validates an output string against a schema.\n *\n * @param output The output string to validate.\n * @param schema The schema to validate against.\n * @return The output map.\n * @throws IllegalArgumentException If the output string does not match the schema.\n * @throws JsonProcessingException If the output string cannot be parsed.\n */\n @SuppressWarnings(\"unchecked\") // For tool parameter type casting.\n public static Map validateOutputSchema(String output, Schema schema)\n throws JsonProcessingException {\n Map outputMap = JsonBaseModel.getMapper().readValue(output, HashMap.class);\n validateMapOnSchema(outputMap, schema, false);\n return outputMap;\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/agents/SequentialAgent.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.agents;\n\nimport com.google.adk.events.Event;\nimport com.google.common.collect.ImmutableList;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport io.reactivex.rxjava3.core.Flowable;\nimport java.util.List;\n\n/** An agent that runs its sub-agents sequentially. */\npublic class SequentialAgent extends BaseAgent {\n\n /**\n * Constructor for SequentialAgent.\n *\n * @param name The agent's name.\n * @param description The agent's description.\n * @param subAgents The list of sub-agents to run sequentially.\n * @param beforeAgentCallback Optional callback before the agent runs.\n * @param afterAgentCallback Optional callback after the agent runs.\n */\n private SequentialAgent(\n String name,\n String description,\n List subAgents,\n List beforeAgentCallback,\n List afterAgentCallback) {\n\n super(name, description, subAgents, beforeAgentCallback, afterAgentCallback);\n }\n\n /** Builder for {@link SequentialAgent}. */\n public static class Builder {\n private String name;\n private String description;\n private List subAgents;\n private ImmutableList beforeAgentCallback;\n private ImmutableList afterAgentCallback;\n\n @CanIgnoreReturnValue\n public Builder name(String name) {\n this.name = name;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder description(String description) {\n this.description = description;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder subAgents(List subAgents) {\n this.subAgents = subAgents;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder subAgents(BaseAgent... subAgents) {\n this.subAgents = ImmutableList.copyOf(subAgents);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeAgentCallback(Callbacks.BeforeAgentCallback beforeAgentCallback) {\n this.beforeAgentCallback = ImmutableList.of(beforeAgentCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeAgentCallback(\n List beforeAgentCallback) {\n this.beforeAgentCallback = CallbackUtil.getBeforeAgentCallbacks(beforeAgentCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterAgentCallback(Callbacks.AfterAgentCallback afterAgentCallback) {\n this.afterAgentCallback = ImmutableList.of(afterAgentCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterAgentCallback(List afterAgentCallback) {\n this.afterAgentCallback = CallbackUtil.getAfterAgentCallbacks(afterAgentCallback);\n return this;\n }\n\n public SequentialAgent build() {\n // TODO(b/410859954): Add validation for required fields like name.\n return new SequentialAgent(\n name, description, subAgents, beforeAgentCallback, afterAgentCallback);\n }\n }\n\n public static Builder builder() {\n return new Builder();\n }\n\n /**\n * Runs sub-agents sequentially.\n *\n * @param invocationContext Invocation context.\n * @return Flowable emitting events from sub-agents.\n */\n @Override\n protected Flowable runAsyncImpl(InvocationContext invocationContext) {\n return Flowable.fromIterable(subAgents())\n .concatMap(subAgent -> subAgent.runAsync(invocationContext));\n }\n\n /**\n * Runs sub-agents sequentially in live mode.\n *\n * @param invocationContext Invocation context.\n * @return Flowable emitting events from sub-agents in live mode.\n */\n @Override\n protected Flowable runLiveImpl(InvocationContext invocationContext) {\n return Flowable.fromIterable(subAgents())\n .concatMap(subAgent -> subAgent.runLive(invocationContext));\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/artifacts/BaseArtifactService.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.artifacts;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.genai.types.Part;\nimport io.reactivex.rxjava3.core.Completable;\nimport io.reactivex.rxjava3.core.Maybe;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.Optional;\n\n/** Base interface for artifact services. */\npublic interface BaseArtifactService {\n\n /**\n * Saves an artifact.\n *\n * @param appName the app name\n * @param userId the user ID\n * @param sessionId the session ID\n * @param filename the filename\n * @param artifact the artifact\n * @return the revision ID (version) of the saved artifact.\n */\n Single saveArtifact(\n String appName, String userId, String sessionId, String filename, Part artifact);\n\n /**\n * Gets an artifact.\n *\n * @param appName the app name\n * @param userId the user ID\n * @param sessionId the session ID\n * @param filename the filename\n * @param version Optional version number. If null, loads the latest version.\n * @return the artifact or empty if not found\n */\n Maybe loadArtifact(\n String appName, String userId, String sessionId, String filename, Optional version);\n\n /**\n * Lists all the artifact filenames within a session.\n *\n * @param appName the app name\n * @param userId the user ID\n * @param sessionId the session ID\n * @return the list artifact response containing filenames\n */\n Single listArtifactKeys(String appName, String userId, String sessionId);\n\n /**\n * Deletes an artifact.\n *\n * @param appName the app name\n * @param userId the user ID\n * @param sessionId the session ID\n * @param filename the filename\n */\n Completable deleteArtifact(String appName, String userId, String sessionId, String filename);\n\n /**\n * Lists all the versions (as revision IDs) of an artifact.\n *\n * @param appName the app name\n * @param userId the user ID\n * @param sessionId the session ID\n * @param filename the artifact filename\n * @return A list of integer version numbers.\n */\n Single> listVersions(\n String appName, String userId, String sessionId, String filename);\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/llmflows/Basic.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows.llmflows;\n\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.agents.LlmAgent;\nimport com.google.adk.models.LlmRequest;\nimport com.google.common.collect.ImmutableList;\nimport com.google.genai.types.GenerateContentConfig;\nimport com.google.genai.types.LiveConnectConfig;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.Optional;\n\n/** {@link RequestProcessor} that handles basic information to build the LLM request. */\npublic final class Basic implements RequestProcessor {\n\n public Basic() {}\n\n @Override\n public Single processRequest(\n InvocationContext context, LlmRequest request) {\n if (!(context.agent() instanceof LlmAgent)) {\n throw new IllegalArgumentException(\"Agent in InvocationContext is not an instance of Agent.\");\n }\n LlmAgent agent = (LlmAgent) context.agent();\n String modelName =\n agent.resolvedModel().model().isPresent()\n ? agent.resolvedModel().model().get().model()\n : agent.resolvedModel().modelName().get();\n\n LiveConnectConfig.Builder liveConnectConfigBuilder =\n LiveConnectConfig.builder().responseModalities(context.runConfig().responseModalities());\n Optional.ofNullable(context.runConfig().speechConfig())\n .ifPresent(liveConnectConfigBuilder::speechConfig);\n Optional.ofNullable(context.runConfig().outputAudioTranscription())\n .ifPresent(liveConnectConfigBuilder::outputAudioTranscription);\n\n LlmRequest.Builder builder =\n request.toBuilder()\n .model(modelName)\n .config(agent.generateContentConfig().orElse(GenerateContentConfig.builder().build()))\n .liveConnectConfig(liveConnectConfigBuilder.build());\n\n agent.outputSchema().ifPresent(builder::outputSchema);\n return Single.just(\n RequestProcessor.RequestProcessingResult.create(builder.build(), ImmutableList.of()));\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/utils/Pairs.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.utils;\n\nimport com.google.common.collect.ImmutableMap;\nimport java.util.concurrent.ConcurrentHashMap;\n\n/** Utility class for creating ConcurrentHashMaps. */\npublic final class Pairs {\n\n private Pairs() {}\n\n /**\n * Returns a new, empty {@code ConcurrentHashMap}.\n *\n * @param the {@code ConcurrentHashMap}'s key type\n * @param the {@code ConcurrentHashMap}'s value type\n * @return an empty {@code ConcurrentHashMap}\n */\n public static ConcurrentHashMap of() {\n return new ConcurrentHashMap<>();\n }\n\n /**\n * Returns a new {@code ConcurrentHashMap} containing a single mapping.\n *\n * @param the {@code ConcurrentHashMap}'s key type\n * @param the {@code ConcurrentHashMap}'s value type\n * @param k1 the mapping's key\n * @param v1 the mapping's value\n * @return a {@code ConcurrentHashMap} containing the specified mapping\n * @throws NullPointerException if the key or the value is {@code null}\n */\n public static ConcurrentHashMap of(K k1, V v1) {\n return new ConcurrentHashMap<>(ImmutableMap.of(k1, v1));\n }\n\n /**\n * Returns a new {@code ConcurrentHashMap} containing two mappings. This method leverages {@code\n * java.util.Map.of} for initial validation.\n *\n * @param the {@code ConcurrentHashMap}'s key type\n * @param the {@code ConcurrentHashMap}'s value type\n * @param k1 the first mapping's key\n * @param v1 the first mapping's value\n * @param k2 the second mapping's key\n * @param v2 the second mapping's value\n * @return a {@code ConcurrentHashMap} containing the specified mappings\n */\n public static ConcurrentHashMap of(K k1, V v1, K k2, V v2) {\n return new ConcurrentHashMap<>(ImmutableMap.of(k1, v1, k2, v2));\n }\n\n /**\n * Returns a new {@code ConcurrentHashMap} containing three mappings. This method leverages {@code\n * java.util.Map.of} for initial validation.\n *\n * @param the {@code ConcurrentHashMap}'s key type\n * @param the {@code ConcurrentHashMap}'s value type\n * @param k1 the first mapping's key\n * @param v1 the first mapping's value\n * @param k2 the second mapping's key\n * @param v2 the second mapping's value\n * @param k3 the third mapping's key\n * @param v3 the third mapping's value\n * @return a {@code ConcurrentHashMap} containing the specified mappings\n */\n public static ConcurrentHashMap of(K k1, V v1, K k2, V v2, K k3, V v3) {\n return new ConcurrentHashMap<>(ImmutableMap.of(k1, v1, k2, v2, k3, v3));\n }\n\n /**\n * Returns a new {@code ConcurrentHashMap} containing four mappings. This method leverages {@code\n * java.util.Map.of} for initial validation.\n *\n * @param the {@code ConcurrentHashMap}'s key type\n * @param the {@code ConcurrentHashMap}'s value type\n * @param k1 the first mapping's key\n * @param v1 the first mapping's value\n * @param k2 the second mapping's key\n * @param v2 the second mapping's value\n * @param k3 the third mapping's key\n * @param v3 the third mapping's value\n * @param k4 the fourth mapping's key\n * @param v4 the fourth mapping's value\n * @return a {@code ConcurrentHashMap} containing the specified mappings\n */\n public static ConcurrentHashMap of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {\n return new ConcurrentHashMap<>(ImmutableMap.of(k1, v1, k2, v2, k3, v3, k4, v4));\n }\n\n /**\n * Returns a new {@code ConcurrentHashMap} containing five mappings. This method leverages {@code\n * java.util.Map.of} for initial validation.\n *\n * @param the {@code ConcurrentHashMap}'s key type\n * @param the {@code ConcurrentHashMap}'s value type\n * @param k1 the first mapping's key\n * @param v1 the first mapping's value\n * @param k2 the second mapping's key\n * @param v2 the second mapping's value\n * @param k3 the third mapping's key\n * @param v3 the third mapping's value\n * @param k4 the fourth mapping's key\n * @param v4 the fourth mapping's value\n * @param k5 the fifth mapping's key\n * @param v5 the fifth mapping's value\n * @return a {@code ConcurrentHashMap} containing the specified mappings\n */\n public static ConcurrentHashMap of(\n K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {\n return new ConcurrentHashMap<>(ImmutableMap.of(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5));\n }\n\n /**\n * Returns a new {@code ConcurrentHashMap} containing six mappings. This method leverages {@code\n * java.util.Map.of} for initial validation.\n *\n * @param the {@code ConcurrentHashMap}'s key type\n * @param the {@code ConcurrentHashMap}'s value type\n * @param k1 the first mapping's key\n * @param v1 the first mapping's value\n * @param k2 the second mapping's key\n * @param v2 the second mapping's value\n * @param k3 the third mapping's key\n * @param v3 the third mapping's value\n * @param k4 the fourth mapping's key\n * @param v4 the fourth mapping's value\n * @param k5 the fifth mapping's key\n * @param v5 the fifth mapping's value\n * @param k6 the sixth mapping's key\n * @param v6 the sixth mapping's value\n * @return a {@code ConcurrentHashMap} containing the specified mappings\n * @throws IllegalArgumentException if there are any duplicate keys (behavior inherited from\n * Map.of)\n * @throws NullPointerException if any key or value is {@code null} (behavior inherited from\n * Map.of)\n */\n public static ConcurrentHashMap of(\n K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6) {\n return new ConcurrentHashMap<>(ImmutableMap.of(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6));\n }\n\n /**\n * Returns a new {@code ConcurrentHashMap} containing seven mappings. This method leverages {@code\n * java.util.Map.of} for initial validation.\n *\n * @param the {@code ConcurrentHashMap}'s key type\n * @param the {@code ConcurrentHashMap}'s value type\n * @param k1 the first mapping's key\n * @param v1 the first mapping's value\n * @param k2 the second mapping's key\n * @param v2 the second mapping's value\n * @param k3 the third mapping's key\n * @param v3 the third mapping's value\n * @param k4 the fourth mapping's key\n * @param v4 the fourth mapping's value\n * @param k5 the fifth mapping's key\n * @param v5 the fifth mapping's value\n * @param k6 the sixth mapping's key\n * @param v6 the sixth mapping's value\n * @param k7 the seventh mapping's key\n * @param v7 the seventh mapping's value\n * @return a {@code ConcurrentHashMap} containing the specified mappings\n */\n public static ConcurrentHashMap of(\n K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7) {\n return new ConcurrentHashMap<>(\n ImmutableMap.of(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6, k7, v7));\n }\n\n /**\n * Returns a new {@code ConcurrentHashMap} containing eight mappings. This method leverages {@code\n * java.util.Map.of} for initial validation.\n *\n * @param the {@code ConcurrentHashMap}'s key type\n * @param the {@code ConcurrentHashMap}'s value type\n * @param k1 the first mapping's key\n * @param v1 the first mapping's value\n * @param k2 the second mapping's key\n * @param v2 the second mapping's value\n * @param k3 the third mapping's key\n * @param v3 the third mapping's value\n * @param k4 the fourth mapping's key\n * @param v4 the fourth mapping's value\n * @param k5 the fifth mapping's key\n * @param v5 the fifth mapping's value\n * @param k6 the sixth mapping's key\n * @param v6 the sixth mapping's value\n * @param k7 the seventh mapping's key\n * @param v7 the seventh mapping's value\n * @param k8 the eighth mapping's key\n * @param v8 the eighth mapping's value\n * @return a {@code ConcurrentHashMap} containing the specified mappings\n */\n public static ConcurrentHashMap of(\n K k1,\n V v1,\n K k2,\n V v2,\n K k3,\n V v3,\n K k4,\n V v4,\n K k5,\n V v5,\n K k6,\n V v6,\n K k7,\n V v7,\n K k8,\n V v8) {\n return new ConcurrentHashMap<>(\n ImmutableMap.of(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6, k7, v7, k8, v8));\n }\n\n /**\n * Returns a new {@code ConcurrentHashMap} containing nine mappings. This method leverages {@code\n * java.util.Map.of} for initial validation.\n *\n * @param the {@code ConcurrentHashMap}'s key type\n * @param the {@code ConcurrentHashMap}'s value type\n * @param k1 the first mapping's key\n * @param v1 the first mapping's value\n * @param k2 the second mapping's key\n * @param v2 the second mapping's value\n * @param k3 the third mapping's key\n * @param v3 the third mapping's value\n * @param k4 the fourth mapping's key\n * @param v4 the fourth mapping's value\n * @param k5 the fifth mapping's key\n * @param v5 the fifth mapping's value\n * @param k6 the sixth mapping's key\n * @param v6 the sixth mapping's value\n * @param k7 the seventh mapping's key\n * @param v7 the seventh mapping's value\n * @param k8 the eighth mapping's key\n * @param v8 the eighth mapping's value\n * @param k9 the ninth mapping's key\n * @param v9 the ninth mapping's value\n * @return a {@code ConcurrentHashMap} containing the specified mappings\n */\n public static ConcurrentHashMap of(\n K k1,\n V v1,\n K k2,\n V v2,\n K k3,\n V v3,\n K k4,\n V v4,\n K k5,\n V v5,\n K k6,\n V v6,\n K k7,\n V v7,\n K k8,\n V v8,\n K k9,\n V v9) {\n return new ConcurrentHashMap<>(\n ImmutableMap.of(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6, k7, v7, k8, v8, k9, v9));\n }\n\n /**\n * Returns a new {@code ConcurrentHashMap} containing ten mappings. This method leverages {@code\n * java.util.Map.of} for initial validation.\n *\n * @param the {@code ConcurrentHashMap}'s key type\n * @param the {@code ConcurrentHashMap}'s value type\n * @param k1 the first mapping's key\n * @param v1 the first mapping's value\n * @param k2 the second mapping's key\n * @param v2 the second mapping's value\n * @param k3 the third mapping's key\n * @param v3 the third mapping's value\n * @param k4 the fourth mapping's key\n * @param v4 the fourth mapping's value\n * @param k5 the fifth mapping's key\n * @param v5 the fifth mapping's value\n * @param k6 the sixth mapping's key\n * @param v6 the sixth mapping's value\n * @param k7 the seventh mapping's key\n * @param v7 the seventh mapping's value\n * @param k8 the eighth mapping's key\n * @param v8 the eighth mapping's value\n * @param k9 the ninth mapping's key\n * @param v9 the ninth mapping's value\n * @param k10 the tenth mapping's key\n * @param v10 the tenth mapping's value\n * @return a {@code ConcurrentHashMap} containing the specified mappings\n */\n public static ConcurrentHashMap of(\n K k1,\n V v1,\n K k2,\n V v2,\n K k3,\n V v3,\n K k4,\n V v4,\n K k5,\n V v5,\n K k6,\n V v6,\n K k7,\n V v7,\n K k8,\n V v8,\n K k9,\n V v9,\n K k10,\n V v10) {\n return new ConcurrentHashMap<>(\n ImmutableMap.of(\n k1, v1, k2, v2, k3, v3, k4, v4, k5, v5, k6, v6, k7, v7, k8, v8, k9, v9, k10, v10));\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/BuiltInCodeExecutionTool.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools;\n\nimport com.google.adk.models.LlmRequest;\nimport com.google.common.collect.ImmutableList;\nimport com.google.genai.types.GenerateContentConfig;\nimport com.google.genai.types.Tool;\nimport com.google.genai.types.ToolCodeExecution;\nimport io.reactivex.rxjava3.core.Completable;\nimport java.util.List;\n\n/**\n * A built-in code execution tool that is automatically invoked by Gemini 2 models.\n *\n *

This tool operates internally within the model and does not require or perform local code\n * execution.\n */\npublic final class BuiltInCodeExecutionTool extends BaseTool {\n\n public BuiltInCodeExecutionTool() {\n super(\"code_execution\", \"code_execution\");\n }\n\n @Override\n public Completable processLlmRequest(\n LlmRequest.Builder llmRequestBuilder, ToolContext toolContext) {\n\n String model = llmRequestBuilder.build().model().get();\n if (model.isEmpty() || !model.startsWith(\"gemini-2\")) {\n return Completable.error(\n new IllegalArgumentException(\"Code execution tool is not supported for model \" + model));\n }\n GenerateContentConfig.Builder configBuilder =\n llmRequestBuilder\n .build()\n .config()\n .map(GenerateContentConfig::toBuilder)\n .orElse(GenerateContentConfig.builder());\n\n List existingTools = configBuilder.build().tools().orElse(ImmutableList.of());\n ImmutableList.Builder updatedToolsBuilder = ImmutableList.builder();\n updatedToolsBuilder\n .addAll(existingTools)\n .add(Tool.builder().codeExecution(ToolCodeExecution.builder().build()).build());\n configBuilder.tools(updatedToolsBuilder.build());\n llmRequestBuilder.config(configBuilder.build());\n return Completable.complete();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/agents/ParallelAgent.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.agents;\n\nimport static com.google.common.base.Strings.isNullOrEmpty;\n\nimport com.google.adk.events.Event;\nimport com.google.common.collect.ImmutableList;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport io.reactivex.rxjava3.core.Flowable;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * A shell agent that runs its sub-agents in parallel in isolated manner.\n *\n *

This approach is beneficial for scenarios requiring multiple perspectives or attempts on a\n * single task, such as running different algorithms simultaneously or generating multiple responses\n * for review by a subsequent evaluation agent.\n */\npublic class ParallelAgent extends BaseAgent {\n\n /**\n * Constructor for ParallelAgent.\n *\n * @param name The agent's name.\n * @param description The agent's description.\n * @param subAgents The list of sub-agents to run sequentially.\n * @param beforeAgentCallback Optional callback before the agent runs.\n * @param afterAgentCallback Optional callback after the agent runs.\n */\n private ParallelAgent(\n String name,\n String description,\n List subAgents,\n List beforeAgentCallback,\n List afterAgentCallback) {\n\n super(name, description, subAgents, beforeAgentCallback, afterAgentCallback);\n }\n\n /** Builder for {@link ParallelAgent}. */\n public static class Builder {\n private String name;\n private String description;\n private List subAgents;\n private ImmutableList beforeAgentCallback;\n private ImmutableList afterAgentCallback;\n\n @CanIgnoreReturnValue\n public Builder name(String name) {\n this.name = name;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder description(String description) {\n this.description = description;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder subAgents(List subAgents) {\n this.subAgents = subAgents;\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder subAgents(BaseAgent... subAgents) {\n this.subAgents = ImmutableList.copyOf(subAgents);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeAgentCallback(Callbacks.BeforeAgentCallback beforeAgentCallback) {\n this.beforeAgentCallback = ImmutableList.of(beforeAgentCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder beforeAgentCallback(\n List beforeAgentCallback) {\n this.beforeAgentCallback = CallbackUtil.getBeforeAgentCallbacks(beforeAgentCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterAgentCallback(Callbacks.AfterAgentCallback afterAgentCallback) {\n this.afterAgentCallback = ImmutableList.of(afterAgentCallback);\n return this;\n }\n\n @CanIgnoreReturnValue\n public Builder afterAgentCallback(List afterAgentCallback) {\n this.afterAgentCallback = CallbackUtil.getAfterAgentCallbacks(afterAgentCallback);\n return this;\n }\n\n public ParallelAgent build() {\n return new ParallelAgent(\n name, description, subAgents, beforeAgentCallback, afterAgentCallback);\n }\n }\n\n public static Builder builder() {\n return new Builder();\n }\n\n /**\n * Sets the branch for the current agent in the invocation context.\n *\n *

Appends the agent name to the current branch, or sets it if undefined.\n *\n * @param currentAgent Current agent.\n * @param invocationContext Invocation context to update.\n */\n private static void setBranchForCurrentAgent(\n BaseAgent currentAgent, InvocationContext invocationContext) {\n String branch = invocationContext.branch().orElse(null);\n if (isNullOrEmpty(branch)) {\n invocationContext.branch(currentAgent.name());\n } else {\n invocationContext.branch(branch + \".\" + currentAgent.name());\n }\n }\n\n /**\n * Runs sub-agents in parallel and emits their events.\n *\n *

Sets the branch and merges event streams from all sub-agents.\n *\n * @param invocationContext Invocation context.\n * @return Flowable emitting events from all sub-agents.\n */\n @Override\n protected Flowable runAsyncImpl(InvocationContext invocationContext) {\n setBranchForCurrentAgent(this, invocationContext);\n\n List currentSubAgents = subAgents();\n if (currentSubAgents == null || currentSubAgents.isEmpty()) {\n return Flowable.empty();\n }\n\n List> agentFlowables = new ArrayList<>();\n for (BaseAgent subAgent : currentSubAgents) {\n agentFlowables.add(subAgent.runAsync(invocationContext));\n }\n return Flowable.merge(agentFlowables);\n }\n\n /**\n * Not supported for ParallelAgent.\n *\n * @param invocationContext Invocation context.\n * @return Flowable that always throws UnsupportedOperationException.\n */\n @Override\n protected Flowable runLiveImpl(InvocationContext invocationContext) {\n return Flowable.error(\n new UnsupportedOperationException(\"runLive is not defined for ParallelAgent yet.\"));\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/agents/RunConfig.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.agents;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport com.google.genai.types.AudioTranscriptionConfig;\nimport com.google.genai.types.Modality;\nimport com.google.genai.types.SpeechConfig;\nimport org.jspecify.annotations.Nullable;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/** Configuration to modify an agent's LLM's underlying behavior. */\n@AutoValue\npublic abstract class RunConfig {\n private static final Logger logger = LoggerFactory.getLogger(RunConfig.class);\n\n /** Streaming mode for the runner. Required for BaseAgent.runLive() to work. */\n public enum StreamingMode {\n NONE,\n SSE,\n BIDI\n }\n\n public abstract @Nullable SpeechConfig speechConfig();\n\n public abstract ImmutableList responseModalities();\n\n public abstract boolean saveInputBlobsAsArtifacts();\n\n public abstract StreamingMode streamingMode();\n\n public abstract @Nullable AudioTranscriptionConfig outputAudioTranscription();\n\n public abstract int maxLlmCalls();\n\n public static Builder builder() {\n return new AutoValue_RunConfig.Builder()\n .setSaveInputBlobsAsArtifacts(false)\n .setResponseModalities(ImmutableList.of())\n .setStreamingMode(StreamingMode.NONE)\n .setMaxLlmCalls(500);\n }\n\n public static Builder builder(RunConfig runConfig) {\n return new AutoValue_RunConfig.Builder()\n .setSaveInputBlobsAsArtifacts(runConfig.saveInputBlobsAsArtifacts())\n .setStreamingMode(runConfig.streamingMode())\n .setMaxLlmCalls(runConfig.maxLlmCalls())\n .setResponseModalities(runConfig.responseModalities())\n .setSpeechConfig(runConfig.speechConfig())\n .setOutputAudioTranscription(runConfig.outputAudioTranscription());\n }\n\n /** Builder for {@link RunConfig}. */\n @AutoValue.Builder\n public abstract static class Builder {\n\n @CanIgnoreReturnValue\n public abstract Builder setSpeechConfig(SpeechConfig speechConfig);\n\n @CanIgnoreReturnValue\n public abstract Builder setResponseModalities(Iterable responseModalities);\n\n @CanIgnoreReturnValue\n public abstract Builder setSaveInputBlobsAsArtifacts(boolean saveInputBlobsAsArtifacts);\n\n @CanIgnoreReturnValue\n public abstract Builder setStreamingMode(StreamingMode streamingMode);\n\n @CanIgnoreReturnValue\n public abstract Builder setOutputAudioTranscription(\n AudioTranscriptionConfig outputAudioTranscription);\n\n @CanIgnoreReturnValue\n public abstract Builder setMaxLlmCalls(int maxLlmCalls);\n\n abstract RunConfig autoBuild();\n\n public RunConfig build() {\n RunConfig runConfig = autoBuild();\n if (runConfig.maxLlmCalls() < 0) {\n logger.warn(\n \"maxLlmCalls is negative. This will result in no enforcement on total\"\n + \" number of llm calls that will be made for a run. This may not be ideal, as this\"\n + \" could result in a never ending communication between the model and the agent in\"\n + \" certain cases.\");\n }\n return runConfig;\n }\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/sessions/SessionUtils.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.genai.types.Blob;\nimport com.google.genai.types.Content;\nimport com.google.genai.types.Part;\nimport java.util.ArrayList;\nimport java.util.Base64;\nimport java.util.List;\nimport java.util.Optional;\n\n/** Utility functions for session service. */\npublic final class SessionUtils {\n\n public SessionUtils() {}\n\n /** Base64-encodes inline blobs in content. */\n public static Content encodeContent(Content content) {\n List encodedParts = new ArrayList<>();\n for (Part part : content.parts().orElse(ImmutableList.of())) {\n boolean isInlineDataPresent = false;\n if (part.inlineData() != null) {\n Optional inlineDataOptional = part.inlineData();\n if (inlineDataOptional.isPresent()) {\n Blob inlineDataBlob = inlineDataOptional.get();\n Optional dataOptional = inlineDataBlob.data();\n if (dataOptional.isPresent()) {\n byte[] dataBytes = dataOptional.get();\n byte[] encodedData = Base64.getEncoder().encode(dataBytes);\n encodedParts.add(\n part.toBuilder().inlineData(Blob.builder().data(encodedData).build()).build());\n isInlineDataPresent = true;\n }\n }\n }\n if (!isInlineDataPresent) {\n encodedParts.add(part);\n }\n }\n return toContent(encodedParts, content.role());\n }\n\n /** Decodes Base64-encoded inline blobs in content. */\n public static Content decodeContent(Content content) {\n List decodedParts = new ArrayList<>();\n for (Part part : content.parts().orElse(ImmutableList.of())) {\n boolean isInlineDataPresent = false;\n if (part.inlineData() != null) {\n Optional inlineDataOptional = part.inlineData();\n if (inlineDataOptional.isPresent()) {\n Blob inlineDataBlob = inlineDataOptional.get();\n Optional dataOptional = inlineDataBlob.data();\n if (dataOptional.isPresent()) {\n byte[] dataBytes = dataOptional.get();\n byte[] decodedData = Base64.getDecoder().decode(dataBytes);\n decodedParts.add(\n part.toBuilder().inlineData(Blob.builder().data(decodedData).build()).build());\n isInlineDataPresent = true;\n }\n }\n }\n if (!isInlineDataPresent) {\n decodedParts.add(part);\n }\n }\n return toContent(decodedParts, content.role());\n }\n\n /** Builds content from parts and optional role. */\n private static Content toContent(List parts, Optional role) {\n Content.Builder contentBuilder = Content.builder().parts(parts);\n role.ifPresent(contentBuilder::role);\n return contentBuilder.build();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/agents/CallbackUtil.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.agents;\n\nimport com.google.adk.agents.Callbacks.AfterAgentCallback;\nimport com.google.adk.agents.Callbacks.AfterAgentCallbackBase;\nimport com.google.adk.agents.Callbacks.AfterAgentCallbackSync;\nimport com.google.adk.agents.Callbacks.BeforeAgentCallback;\nimport com.google.adk.agents.Callbacks.BeforeAgentCallbackBase;\nimport com.google.adk.agents.Callbacks.BeforeAgentCallbackSync;\nimport com.google.common.collect.ImmutableList;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport io.reactivex.rxjava3.core.Maybe;\nimport java.util.List;\nimport org.jspecify.annotations.Nullable;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\n/** Utility methods for normalizing agent callbacks. */\npublic final class CallbackUtil {\n private static final Logger logger = LoggerFactory.getLogger(CallbackUtil.class);\n\n /**\n * Normalizes before-agent callbacks.\n *\n * @param beforeAgentCallback Callback list (sync or async).\n * @return normalized async callbacks, or null if input is null.\n */\n @CanIgnoreReturnValue\n public static @Nullable ImmutableList getBeforeAgentCallbacks(\n List beforeAgentCallback) {\n if (beforeAgentCallback == null) {\n return null;\n } else if (beforeAgentCallback.isEmpty()) {\n return ImmutableList.of();\n } else {\n ImmutableList.Builder builder = ImmutableList.builder();\n for (BeforeAgentCallbackBase callback : beforeAgentCallback) {\n if (callback instanceof BeforeAgentCallback beforeAgentCallbackInstance) {\n builder.add(beforeAgentCallbackInstance);\n } else if (callback instanceof BeforeAgentCallbackSync beforeAgentCallbackSyncInstance) {\n builder.add(\n (BeforeAgentCallback)\n (callbackContext) ->\n Maybe.fromOptional(beforeAgentCallbackSyncInstance.call(callbackContext)));\n } else {\n logger.warn(\n \"Invalid beforeAgentCallback callback type: %s. Ignoring this callback.\",\n callback.getClass().getName());\n }\n }\n return builder.build();\n }\n }\n\n /**\n * Normalizes after-agent callbacks.\n *\n * @param afterAgentCallback Callback list (sync or async).\n * @return normalized async callbacks, or null if input is null.\n */\n @CanIgnoreReturnValue\n public static @Nullable ImmutableList getAfterAgentCallbacks(\n List afterAgentCallback) {\n if (afterAgentCallback == null) {\n return null;\n } else if (afterAgentCallback.isEmpty()) {\n return ImmutableList.of();\n } else {\n ImmutableList.Builder builder = ImmutableList.builder();\n for (AfterAgentCallbackBase callback : afterAgentCallback) {\n if (callback instanceof AfterAgentCallback afterAgentCallbackInstance) {\n builder.add(afterAgentCallbackInstance);\n } else if (callback instanceof AfterAgentCallbackSync afterAgentCallbackSyncInstance) {\n builder.add(\n (AfterAgentCallback)\n (callbackContext) ->\n Maybe.fromOptional(afterAgentCallbackSyncInstance.call(callbackContext)));\n } else {\n logger.warn(\n \"Invalid afterAgentCallback callback type: %s. Ignoring this callback.\",\n callback.getClass().getName());\n }\n }\n return builder.build();\n }\n }\n\n private CallbackUtil() {}\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/sessions/ListSessionsResponse.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\nimport static com.google.common.collect.ImmutableList.toImmutableList;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\nimport java.util.List;\n\n/** Response for listing sessions. */\n@AutoValue\npublic abstract class ListSessionsResponse {\n\n public abstract ImmutableList sessions();\n\n public List sessionIds() {\n return sessions().stream().map(Session::id).collect(toImmutableList());\n }\n\n /** Builder for {@link ListSessionsResponse}. */\n @AutoValue.Builder\n public abstract static class Builder {\n\n public abstract Builder sessions(List sessions);\n\n public abstract ListSessionsResponse build();\n }\n\n public static Builder builder() {\n return new AutoValue_ListSessionsResponse.Builder().sessions(ImmutableList.of());\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/llmflows/Examples.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows.llmflows;\n\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.agents.LlmAgent;\nimport com.google.adk.examples.ExampleUtils;\nimport com.google.adk.models.LlmRequest;\nimport com.google.common.collect.ImmutableList;\nimport io.reactivex.rxjava3.core.Single;\n\n/** {@link RequestProcessor} that populates examples in LLM request. */\npublic final class Examples implements RequestProcessor {\n\n public Examples() {}\n\n @Override\n public Single processRequest(\n InvocationContext context, LlmRequest request) {\n if (!(context.agent() instanceof LlmAgent)) {\n throw new IllegalArgumentException(\"Agent in InvocationContext is not an instance of Agent.\");\n }\n LlmAgent agent = (LlmAgent) context.agent();\n LlmRequest.Builder builder = request.toBuilder();\n\n String query =\n context.userContent().isPresent()\n ? context.userContent().get().parts().get().get(0).text().orElse(\"\")\n : \"\";\n agent\n .exampleProvider()\n .ifPresent(\n exampleProvider ->\n builder.appendInstructions(\n ImmutableList.of(ExampleUtils.buildExampleSi(exampleProvider, query))));\n return Single.just(\n RequestProcessor.RequestProcessingResult.create(builder.build(), ImmutableList.of()));\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/events/EventStream.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.events;\n\nimport java.util.Iterator;\nimport java.util.NoSuchElementException;\nimport java.util.function.Supplier;\n\n/** Iterable stream of {@link Event} objects. */\npublic class EventStream implements Iterable {\n\n private final Supplier eventSupplier;\n\n /** Constructs a new event stream. */\n public EventStream(Supplier eventSupplier) {\n this.eventSupplier = eventSupplier;\n }\n\n /** Returns an iterator that fetches events lazily. */\n @Override\n public Iterator iterator() {\n return new EventIterator();\n }\n\n /** Iterator that returns events from the supplier until it returns {@code null}. */\n private class EventIterator implements Iterator {\n private Event nextEvent = null;\n private boolean finished = false;\n\n /** Returns {@code true} if another event is available. */\n @Override\n public boolean hasNext() {\n if (finished) {\n return false;\n }\n if (nextEvent == null) {\n nextEvent = eventSupplier.get();\n finished = (nextEvent == null);\n }\n return !finished;\n }\n\n /**\n * Returns the next event.\n *\n * @throws NoSuchElementException if no more events are available.\n */\n @Override\n public Event next() {\n if (!hasNext()) {\n throw new NoSuchElementException(\"No more events.\");\n }\n Event currentEvent = nextEvent;\n nextEvent = null;\n return currentEvent;\n }\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/memory/MemoryEntry.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.memory;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.genai.types.Content;\nimport java.time.Instant;\nimport javax.annotation.Nullable;\n\n/** Represents one memory entry. */\n@AutoValue\npublic abstract class MemoryEntry {\n\n /** Returns the main content of the memory. */\n public abstract Content content();\n\n /** Returns the author of the memory, or null if not set. */\n @Nullable\n public abstract String author();\n\n /**\n * Returns the timestamp when the original content of this memory happened, or null if not set.\n *\n *

This string will be forwarded to LLM. Preferred format is ISO 8601 format\n */\n @Nullable\n public abstract String timestamp();\n\n /** Returns a new builder for creating a {@link MemoryEntry}. */\n public static Builder builder() {\n return new AutoValue_MemoryEntry.Builder();\n }\n\n /**\n * Creates a new builder with a copy of this entry's values.\n *\n * @return a new {@link Builder} instance.\n */\n public abstract Builder toBuilder();\n\n /** Builder for {@link MemoryEntry}. */\n @AutoValue.Builder\n public abstract static class Builder {\n\n /**\n * Sets the main content of the memory.\n *\n *

This is a required field.\n */\n public abstract Builder setContent(Content content);\n\n /** Sets the author of the memory. */\n public abstract Builder setAuthor(@Nullable String author);\n\n /** Sets the timestamp when the original content of this memory happened. */\n public abstract Builder setTimestamp(@Nullable String timestamp);\n\n /**\n * A convenience method to set the timestamp from an {@link Instant} object, formatted as an ISO\n * 8601 string.\n *\n * @param instant The timestamp as an Instant object.\n */\n public Builder setTimestamp(Instant instant) {\n return setTimestamp(instant.toString());\n }\n\n /** Builds the immutable {@link MemoryEntry} object. */\n public abstract MemoryEntry build();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/sessions/GetSessionConfig.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\nimport com.google.auto.value.AutoValue;\nimport java.time.Instant;\nimport java.util.Optional;\n\n/** Configuration for getting a session. */\n@AutoValue\npublic abstract class GetSessionConfig {\n\n public abstract Optional numRecentEvents();\n\n public abstract Optional afterTimestamp();\n\n /** Builder for {@link GetSessionConfig}. */\n @AutoValue.Builder\n public abstract static class Builder {\n\n public abstract Builder numRecentEvents(int numRecentEvents);\n\n public abstract Builder afterTimestamp(Instant afterTimestamp);\n\n public abstract GetSessionConfig build();\n }\n\n public static Builder builder() {\n return new AutoValue_GetSessionConfig.Builder();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/agents/LiveRequest.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.agents;\n\nimport com.fasterxml.jackson.annotation.JsonCreator;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.databind.annotation.JsonDeserialize;\nimport com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;\nimport com.google.adk.JsonBaseModel;\nimport com.google.auto.value.AutoValue;\nimport com.google.common.base.Preconditions;\nimport com.google.genai.types.Blob;\nimport com.google.genai.types.Content;\nimport java.util.Optional;\nimport javax.annotation.Nullable;\n\n/** Represents a request to be sent to a live connection to the LLM model. */\n@AutoValue\n@JsonDeserialize(builder = LiveRequest.Builder.class)\npublic abstract class LiveRequest extends JsonBaseModel {\n\n LiveRequest() {}\n\n /**\n * Returns the content of the request.\n *\n *

If set, send the content to the model in turn-by-turn mode.\n *\n * @return An optional {@link Content} object containing the content of the request.\n */\n @JsonProperty(\"content\")\n public abstract Optional content();\n\n /**\n * Returns the blob of the request.\n *\n *

If set, send the blob to the model in realtime mode.\n *\n * @return An optional {@link Blob} object containing the blob of the request.\n */\n @JsonProperty(\"blob\")\n public abstract Optional blob();\n\n /**\n * Returns whether the connection should be closed.\n *\n *

If set to true, the connection will be closed after the request is sent.\n *\n * @return A boolean indicating whether the connection should be closed.\n */\n @JsonProperty(\"close\")\n public abstract Optional close();\n\n /** Extracts boolean value from the close field or returns false if unset. */\n public boolean shouldClose() {\n return close().orElse(false);\n }\n\n /** Builder for constructing {@link LiveRequest} instances. */\n @AutoValue.Builder\n @JsonPOJOBuilder(buildMethodName = \"build\", withPrefix = \"\")\n public abstract static class Builder {\n @JsonProperty(\"content\")\n public abstract Builder content(@Nullable Content content);\n\n public abstract Builder content(Optional content);\n\n @JsonProperty(\"blob\")\n public abstract Builder blob(@Nullable Blob blob);\n\n public abstract Builder blob(Optional blob);\n\n @JsonProperty(\"close\")\n public abstract Builder close(@Nullable Boolean close);\n\n public abstract Builder close(Optional close);\n\n abstract LiveRequest autoBuild();\n\n public final LiveRequest build() {\n LiveRequest request = autoBuild();\n Preconditions.checkState(\n request.content().isPresent()\n || request.blob().isPresent()\n || request.close().isPresent(),\n \"One of content, blob, or close must be set\");\n return request;\n }\n }\n\n public static Builder builder() {\n return new AutoValue_LiveRequest.Builder().close(false);\n }\n\n public abstract Builder toBuilder();\n\n /** Deserializes a Json string to a {@link LiveRequest} object. */\n public static LiveRequest fromJsonString(String json) {\n return JsonBaseModel.fromJsonString(json, LiveRequest.class);\n }\n\n @JsonCreator\n static LiveRequest.Builder jacksonBuilder() {\n return LiveRequest.builder();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/mcp/DefaultMcpTransportBuilder.java", "package com.google.adk.tools.mcp;\n\nimport com.google.common.collect.ImmutableMap;\nimport io.modelcontextprotocol.client.transport.HttpClientSseClientTransport;\nimport io.modelcontextprotocol.client.transport.ServerParameters;\nimport io.modelcontextprotocol.client.transport.StdioClientTransport;\nimport io.modelcontextprotocol.spec.McpClientTransport;\nimport java.util.Collection;\nimport java.util.Optional;\n\n/**\n * The default builder for creating MCP client transports. Supports StdioClientTransport based on\n * {@link ServerParameters} and the standard HttpClientSseClientTransport based on {@link\n * SseServerParameters}.\n */\npublic class DefaultMcpTransportBuilder implements McpTransportBuilder {\n\n @Override\n public McpClientTransport build(Object connectionParams) {\n if (connectionParams instanceof ServerParameters serverParameters) {\n return new StdioClientTransport(serverParameters);\n } else if (connectionParams instanceof SseServerParameters sseServerParams) {\n return HttpClientSseClientTransport.builder(sseServerParams.url())\n .sseEndpoint(\"sse\")\n .customizeRequest(\n builder ->\n Optional.ofNullable(sseServerParams.headers())\n .map(ImmutableMap::entrySet)\n .stream()\n .flatMap(Collection::stream)\n .forEach(\n entry ->\n builder.header(\n entry.getKey(),\n Optional.ofNullable(entry.getValue())\n .map(Object::toString)\n .orElse(\"\"))))\n .build();\n } else {\n throw new IllegalArgumentException(\n \"DefaultMcpTransportBuilder supports only ServerParameters or SseServerParameters, but\"\n + \" got \"\n + connectionParams.getClass().getName());\n }\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/agents/Instruction.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.agents;\n\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.function.Function;\n\n/**\n * Represents an instruction that can be provided to an agent to guide its behavior.\n *\n *

In the instructions, you should describe concisely what the agent will do, when it should\n * defer to other agents/tools, and how it should respond to the user.\n *\n *

Templating is supported using placeholders like {@code {variable_name}} or {@code\n * {artifact.artifact_name}}. These are replaced with values from the agent's session state or\n * loaded artifacts, respectively. For example, an instruction like {@code \"Translate the following\n * text to {language}: {user_query}\"} would substitute {@code {language}} and {@code {user_query}}\n * with their corresponding values from the session state.\n *\n *

Instructions can also be dynamically constructed using {@link Instruction.Provider}. This\n * allows for more complex logic where the instruction text is generated based on the current {@link\n * ReadonlyContext}. Additionally, an instruction could be built to include specific information\n * based on based on some external factors fetched during the Provider call like the current time,\n * the result of some API call, etc.\n */\npublic sealed interface Instruction permits Instruction.Static, Instruction.Provider {\n /** Plain instruction directly provided to the agent. */\n record Static(String instruction) implements Instruction {}\n\n /** Returns an instruction dynamically constructed from the given context. */\n record Provider(Function> getInstruction)\n implements Instruction {}\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/llmflows/Identity.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows.llmflows;\n\nimport com.google.adk.agents.BaseAgent;\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.models.LlmRequest;\nimport com.google.common.base.Strings;\nimport com.google.common.collect.ImmutableList;\nimport io.reactivex.rxjava3.core.Single;\n\n/** {@link RequestProcessor} that gives the agent identity from the framework */\npublic final class Identity implements RequestProcessor {\n\n public Identity() {}\n\n @Override\n public Single processRequest(\n InvocationContext context, LlmRequest request) {\n BaseAgent agent = context.agent();\n StringBuilder builder =\n new StringBuilder()\n .append(\"You are an agent. Your internal name is \")\n .append(agent.name())\n .append(\".\");\n if (!Strings.isNullOrEmpty(agent.description())) {\n builder.append(\" The description about you is \").append(agent.description());\n }\n return Single.just(\n RequestProcessor.RequestProcessingResult.create(\n request.toBuilder().appendInstructions(ImmutableList.of(builder.toString())).build(),\n ImmutableList.of()));\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/retrieval/BaseRetrievalTool.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools.retrieval;\n\nimport com.google.adk.tools.BaseTool;\nimport com.google.genai.types.FunctionDeclaration;\nimport com.google.genai.types.Schema;\nimport java.util.Collections;\nimport java.util.Optional;\n\n/** Base class for retrieval tools. */\npublic abstract class BaseRetrievalTool extends BaseTool {\n public BaseRetrievalTool(String name, String description) {\n super(name, description);\n }\n\n public BaseRetrievalTool(String name, String description, boolean isLongRunning) {\n super(name, description, isLongRunning);\n }\n\n @Override\n public Optional declaration() {\n Schema querySchema =\n Schema.builder().type(\"STRING\").description(\"The query to retrieve.\").build();\n Schema parametersSchema =\n Schema.builder()\n .type(\"OBJECT\")\n .properties(Collections.singletonMap(\"query\", querySchema))\n .build();\n\n return Optional.of(\n FunctionDeclaration.builder()\n .name(this.name())\n .description(this.description())\n .parameters(parametersSchema)\n .build());\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/runner/InMemoryRunner.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.runner;\n\nimport com.google.adk.agents.BaseAgent;\nimport com.google.adk.artifacts.InMemoryArtifactService;\nimport com.google.adk.sessions.InMemorySessionService;\n\n/** The class for the in-memory GenAi runner, using in-memory artifact and session services. */\npublic class InMemoryRunner extends Runner {\n\n public InMemoryRunner(BaseAgent agent) {\n // TODO: Change the default appName to InMemoryRunner to align with adk python.\n // Check the dev UI in case we break something there.\n this(agent, /* appName= */ agent.name());\n }\n\n public InMemoryRunner(BaseAgent agent, String appName) {\n super(agent, appName, new InMemoryArtifactService(), new InMemorySessionService());\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/network/HttpApiResponse.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.network;\n\nimport com.google.genai.errors.ApiException;\nimport com.google.genai.errors.ClientException;\nimport com.google.genai.errors.ServerException;\nimport java.io.IOException;\nimport okhttp3.Response;\nimport okhttp3.ResponseBody;\n\n/** Wraps a real HTTP response to expose the methods needed by the GenAI SDK. */\npublic final class HttpApiResponse extends ApiResponse {\n\n private final Response response;\n\n /** Constructs a HttpApiResponse instance with the response. */\n public HttpApiResponse(Response response) {\n throwFromResponse(response);\n this.response = response;\n }\n\n /** Returns the ResponseBody from the response. */\n @Override\n public ResponseBody getEntity() {\n return response.body();\n }\n\n /**\n * Throws an ApiException from the response if the response is not a OK status. This method is\n * adapted to work with OkHttp's Response.\n *\n * @param response The response from the API call.\n */\n private void throwFromResponse(Response response) {\n if (response.isSuccessful()) {\n return;\n }\n int code = response.code();\n String status = response.message();\n String message = getErrorMessageFromResponse(response);\n if (code >= 400 && code < 500) { // Client errors.\n throw new ClientException(code, status, message);\n } else if (code >= 500 && code < 600) { // Server errors.\n throw new ServerException(code, status, message);\n } else {\n throw new ApiException(code, status, message);\n }\n }\n\n private String getErrorMessageFromResponse(Response response) {\n try {\n if (response.body() != null) {\n return response.body().string(); // Consume only once.\n }\n } catch (IOException e) {\n // Log the error. Return a generic message to avoid masking original exception.\n return \"Error reading response body\";\n }\n return \"\";\n }\n\n /** Closes the Http response. */\n @Override\n public void close() {\n response.close();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/mcp/SseServerParameters.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools.mcp;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableMap;\nimport java.time.Duration;\nimport java.util.Map;\nimport javax.annotation.Nullable;\n\n/** Parameters for establishing a MCP Server-Sent Events (SSE) connection. */\n@AutoValue\npublic abstract class SseServerParameters {\n\n /** The URL of the SSE server. */\n public abstract String url();\n\n /** Optional headers to include in the SSE connection request. */\n @Nullable\n public abstract ImmutableMap headers();\n\n /** The timeout for the initial connection attempt. */\n public abstract Duration timeout();\n\n /** The timeout for reading data from the SSE stream. */\n public abstract Duration sseReadTimeout();\n\n /** Creates a new builder for {@link SseServerParameters}. */\n public static Builder builder() {\n return new AutoValue_SseServerParameters.Builder()\n .timeout(Duration.ofSeconds(5))\n .sseReadTimeout(Duration.ofMinutes(5));\n }\n\n /** Builder for {@link SseServerParameters}. */\n @AutoValue.Builder\n public abstract static class Builder {\n /** Sets the URL of the SSE server. */\n public abstract Builder url(String url);\n\n /** Sets the headers for the SSE connection request. */\n public abstract Builder headers(@Nullable Map headers);\n\n /** Sets the timeout for the initial connection attempt. */\n public abstract Builder timeout(Duration timeout);\n\n /** Sets the timeout for reading data from the SSE stream. */\n public abstract Builder sseReadTimeout(Duration sseReadTimeout);\n\n /** Builds a new {@link SseServerParameters} instance. */\n public abstract SseServerParameters build();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/BaseToolset.java", "package com.google.adk.tools;\n\nimport com.google.adk.agents.ReadonlyContext;\nimport io.reactivex.rxjava3.core.Flowable;\nimport java.util.List;\nimport java.util.Optional;\n\n/** Base interface for toolsets. */\npublic interface BaseToolset extends AutoCloseable {\n\n /**\n * Return all tools in the toolset based on the provided context.\n *\n * @param readonlyContext Context used to filter tools available to the agent.\n * @return A Single emitting a list of tools available under the specified context.\n */\n Flowable getTools(ReadonlyContext readonlyContext);\n\n /**\n * Performs cleanup and releases resources held by the toolset.\n *\n *

NOTE: This method is invoked, for example, at the end of an agent server's lifecycle or when\n * the toolset is no longer needed. Implementations should ensure that any open connections,\n * files, or other managed resources are properly released to prevent leaks.\n */\n @Override\n void close() throws Exception;\n\n /**\n * Helper method to be used by implementers that returns true if the given tool is in the provided\n * list of tools of if testing against the given ToolPredicate returns true (otherwise false).\n *\n * @param tool The tool to check.\n * @param toolFilter An Optional containing either a ToolPredicate or a List of tool names.\n * @param readonlyContext The current context.\n * @return true if the tool is selected.\n */\n default boolean isToolSelected(\n BaseTool tool, Optional toolFilter, Optional readonlyContext) {\n if (toolFilter.isEmpty()) {\n return true;\n }\n Object filter = toolFilter.get();\n if (filter instanceof ToolPredicate toolPredicate) {\n return toolPredicate.test(tool, readonlyContext);\n }\n if (filter instanceof List) {\n @SuppressWarnings(\"unchecked\")\n List toolNames = (List) filter;\n return toolNames.contains(tool.name());\n }\n return false;\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/JsonBaseModel.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk;\n\nimport com.fasterxml.jackson.annotation.JsonInclude;\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.fasterxml.jackson.databind.DeserializationFeature;\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.fasterxml.jackson.databind.PropertyNamingStrategies;\nimport com.fasterxml.jackson.datatype.jdk8.Jdk8Module;\nimport com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;\n\n/** The base class for the types that needs JSON serialization/deserialization capability. */\npublic abstract class JsonBaseModel {\n\n private static final ObjectMapper objectMapper = new ObjectMapper();\n\n static {\n objectMapper\n .setSerializationInclusion(JsonInclude.Include.NON_ABSENT)\n .setPropertyNamingStrategy(PropertyNamingStrategies.LOWER_CAMEL_CASE)\n .registerModule(new Jdk8Module())\n .registerModule(new JavaTimeModule()) // TODO: echo sec module replace, locale\n .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);\n }\n\n /** Serializes an object to a Json string. */\n protected static String toJsonString(Object object) {\n try {\n return objectMapper.writeValueAsString(object);\n } catch (JsonProcessingException e) {\n throw new IllegalStateException(e);\n }\n }\n\n public static ObjectMapper getMapper() {\n return JsonBaseModel.objectMapper;\n }\n\n public String toJson() {\n return toJsonString(this);\n }\n\n /** Serializes an object to a JsonNode. */\n protected static JsonNode toJsonNode(Object object) {\n return objectMapper.valueToTree(object);\n }\n\n /** Deserializes a Json string to an object of the given type. */\n public static T fromJsonString(String jsonString, Class clazz) {\n try {\n return objectMapper.readValue(jsonString, clazz);\n } catch (JsonProcessingException e) {\n throw new IllegalStateException(e);\n }\n }\n\n /** Deserializes a JsonNode to an object of the given type. */\n public static T fromJsonNode(JsonNode jsonNode, Class clazz) {\n try {\n return objectMapper.treeToValue(jsonNode, clazz);\n } catch (JsonProcessingException e) {\n throw new IllegalStateException(e);\n }\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/llmflows/ResponseProcessor.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows.llmflows;\n\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.events.Event;\nimport com.google.adk.models.LlmResponse;\nimport com.google.auto.value.AutoValue;\nimport io.reactivex.rxjava3.core.Single;\nimport java.util.Optional;\n\npublic interface ResponseProcessor {\n\n @AutoValue\n public abstract static class ResponseProcessingResult {\n public abstract LlmResponse updatedResponse();\n\n public abstract Iterable events();\n\n public abstract Optional transferToAgent();\n\n public static ResponseProcessingResult create(\n LlmResponse updatedResponse, Iterable events, Optional transferToAgent) {\n return new AutoValue_ResponseProcessor_ResponseProcessingResult(\n updatedResponse, events, transferToAgent);\n }\n }\n\n /**\n * Process the LLM response as part of the post-processing stage.\n *\n * @param context the invocation context.\n * @param response the LLM response to process.\n * @return a list of events generated during processing (if any).\n */\n Single processResponse(InvocationContext context, LlmResponse response);\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/BaseFlow.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows;\n\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.events.Event;\nimport io.reactivex.rxjava3.core.Flowable;\n\n/** Interface for the execution flows to run a group of agents. */\npublic interface BaseFlow {\n\n /**\n * Run this flow.\n *\n *

To implement this method, the flow should follow the below requirements:\n *\n *

    \n *
  1. 1. `session` should be treated as immutable, DO NOT change it.\n *
  2. 2. The caller who trigger the flow is responsible for updating the session as the events\n * being generated. The subclass implementation will assume session is updated after each\n * yield event statement.\n *
  3. 3. A flow may spawn sub-agent flows depending on the agent definition.\n *
\n */\n Flowable run(InvocationContext invocationContext);\n\n default Flowable runLive(InvocationContext invocationContext) {\n throw new UnsupportedOperationException(\"Not implemented\");\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/agents/Callbacks.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.agents;\n\nimport com.google.adk.models.LlmRequest;\nimport com.google.adk.models.LlmResponse;\nimport com.google.adk.tools.BaseTool;\nimport com.google.adk.tools.ToolContext;\nimport com.google.genai.types.Content;\nimport io.reactivex.rxjava3.core.Maybe;\nimport java.util.Map;\nimport java.util.Optional;\n\n/** Functional interfaces for agent lifecycle callbacks. */\npublic final class Callbacks {\n\n interface BeforeModelCallbackBase {}\n\n @FunctionalInterface\n public interface BeforeModelCallback extends BeforeModelCallbackBase {\n /**\n * Async callback before LLM invocation.\n *\n * @param callbackContext Callback context.\n * @param llmRequest LLM request.\n * @return response override, or empty to continue.\n */\n Maybe call(CallbackContext callbackContext, LlmRequest llmRequest);\n }\n\n /**\n * Helper interface to allow for sync beforeModelCallback. The function is wrapped into an async\n * one before being processed further.\n */\n @FunctionalInterface\n public interface BeforeModelCallbackSync extends BeforeModelCallbackBase {\n Optional call(CallbackContext callbackContext, LlmRequest llmRequest);\n }\n\n interface AfterModelCallbackBase {}\n\n @FunctionalInterface\n public interface AfterModelCallback extends AfterModelCallbackBase {\n /**\n * Async callback after LLM response.\n *\n * @param callbackContext Callback context.\n * @param llmResponse LLM response.\n * @return modified response, or empty to keep original.\n */\n Maybe call(CallbackContext callbackContext, LlmResponse llmResponse);\n }\n\n /**\n * Helper interface to allow for sync afterModelCallback. The function is wrapped into an async\n * one before being processed further.\n */\n @FunctionalInterface\n public interface AfterModelCallbackSync extends AfterModelCallbackBase {\n Optional call(CallbackContext callbackContext, LlmResponse llmResponse);\n }\n\n interface BeforeAgentCallbackBase {}\n\n @FunctionalInterface\n public interface BeforeAgentCallback extends BeforeAgentCallbackBase {\n /**\n * Async callback before agent runs.\n *\n * @param callbackContext Callback context.\n * @return content override, or empty to continue.\n */\n Maybe call(CallbackContext callbackContext);\n }\n\n /**\n * Helper interface to allow for sync beforeAgentCallback. The function is wrapped into an async\n * one before being processed further.\n */\n @FunctionalInterface\n public interface BeforeAgentCallbackSync extends BeforeAgentCallbackBase {\n Optional call(CallbackContext callbackContext);\n }\n\n interface AfterAgentCallbackBase {}\n\n @FunctionalInterface\n public interface AfterAgentCallback extends AfterAgentCallbackBase {\n /**\n * Async callback after agent runs.\n *\n * @param callbackContext Callback context.\n * @return modified content, or empty to keep original.\n */\n Maybe call(CallbackContext callbackContext);\n }\n\n /**\n * Helper interface to allow for sync afterAgentCallback. The function is wrapped into an async\n * one before being processed further.\n */\n @FunctionalInterface\n public interface AfterAgentCallbackSync extends AfterAgentCallbackBase {\n Optional call(CallbackContext callbackContext);\n }\n\n interface BeforeToolCallbackBase {}\n\n @FunctionalInterface\n public interface BeforeToolCallback extends BeforeToolCallbackBase {\n /**\n * Async callback before tool runs.\n *\n * @param invocationContext Invocation context.\n * @param baseTool Tool instance.\n * @param input Tool input arguments.\n * @param toolContext Tool context.\n * @return override result, or empty to continue.\n */\n Maybe> call(\n InvocationContext invocationContext,\n BaseTool baseTool,\n Map input,\n ToolContext toolContext);\n }\n\n /**\n * Helper interface to allow for sync beforeToolCallback. The function is wrapped into an async\n * one before being processed further.\n */\n @FunctionalInterface\n public interface BeforeToolCallbackSync extends BeforeToolCallbackBase {\n Optional> call(\n InvocationContext invocationContext,\n BaseTool baseTool,\n Map input,\n ToolContext toolContext);\n }\n\n interface AfterToolCallbackBase {}\n\n @FunctionalInterface\n public interface AfterToolCallback extends AfterToolCallbackBase {\n /**\n * Async callback after tool runs.\n *\n * @param invocationContext Invocation context.\n * @param baseTool Tool instance.\n * @param input Tool input arguments.\n * @param toolContext Tool context.\n * @param response Raw tool response.\n * @return processed result, or empty to keep original.\n */\n Maybe> call(\n InvocationContext invocationContext,\n BaseTool baseTool,\n Map input,\n ToolContext toolContext,\n Object response);\n }\n\n /**\n * Helper interface to allow for sync afterToolCallback. The function is wrapped into an async one\n * before being processed further.\n */\n @FunctionalInterface\n public interface AfterToolCallbackSync extends AfterToolCallbackBase {\n Optional> call(\n InvocationContext invocationContext,\n BaseTool baseTool,\n Map input,\n ToolContext toolContext,\n Object response);\n }\n\n private Callbacks() {}\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/llmflows/audio/VertexSpeechClient.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows.llmflows.audio;\n\nimport com.google.cloud.speech.v1.RecognitionAudio;\nimport com.google.cloud.speech.v1.RecognitionConfig;\nimport com.google.cloud.speech.v1.RecognizeResponse;\nimport com.google.cloud.speech.v1.SpeechClient;\nimport java.io.IOException;\n\n/** Implementation of SpeechClientInterface using Vertex AI SpeechClient. */\npublic class VertexSpeechClient implements SpeechClientInterface {\n\n private final SpeechClient speechClient;\n\n /**\n * Constructs a VertexSpeechClient, initializing the underlying Google Cloud SpeechClient.\n *\n * @throws IOException if SpeechClient creation fails.\n */\n public VertexSpeechClient() throws IOException {\n this.speechClient = SpeechClient.create();\n }\n\n /**\n * Performs synchronous speech recognition on the given audio input.\n *\n * @param config Recognition configuration (e.g., language, encoding).\n * @param audio Audio data to recognize.\n * @return The recognition result.\n */\n @Override\n public RecognizeResponse recognize(RecognitionConfig config, RecognitionAudio audio) {\n // The original SpeechClient.recognize doesn't declare checked exceptions other than what might\n // be runtime. The interface declares Exception to be more general for other implementations.\n return speechClient.recognize(config, audio);\n }\n\n @Override\n public void close() throws Exception {\n if (speechClient != null) {\n speechClient.close();\n }\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/sessions/ListEventsResponse.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\nimport com.google.adk.events.Event;\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\nimport java.util.List;\nimport java.util.Optional;\n\n/** Response for listing events. */\n@AutoValue\npublic abstract class ListEventsResponse {\n\n public abstract ImmutableList events();\n\n public abstract Optional nextPageToken();\n\n /** Builder for {@link ListEventsResponse}. */\n @AutoValue.Builder\n public abstract static class Builder {\n\n public abstract Builder events(List events);\n\n public abstract Builder nextPageToken(String nextPageToken);\n\n public abstract ListEventsResponse build();\n }\n\n public static Builder builder() {\n return new AutoValue_ListEventsResponse.Builder().events(ImmutableList.of());\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/llmflows/RequestProcessor.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows.llmflows;\n\nimport com.google.adk.agents.InvocationContext;\nimport com.google.adk.events.Event;\nimport com.google.adk.models.LlmRequest;\nimport com.google.auto.value.AutoValue;\nimport io.reactivex.rxjava3.core.Single;\n\npublic interface RequestProcessor {\n\n @AutoValue\n public abstract static class RequestProcessingResult {\n public abstract LlmRequest updatedRequest();\n\n public abstract Iterable events();\n\n public static RequestProcessingResult create(\n LlmRequest updatedRequest, Iterable events) {\n return new AutoValue_RequestProcessor_RequestProcessingResult(updatedRequest, events);\n }\n }\n\n /**\n * Process the LLM request as part of the pre-processing stage.\n *\n * @param context the invocation context.\n * @param request the LLM request to process.\n * @return a list of events generated during processing (if any).\n */\n Single processRequest(InvocationContext context, LlmRequest request);\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/llmflows/AutoFlow.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows.llmflows;\n\nimport com.google.common.collect.ImmutableList;\nimport java.util.Optional;\n\n/** LLM flow with automatic agent transfer support. */\npublic class AutoFlow extends SingleFlow {\n\n /** Adds {@link AgentTransfer} to base request processors. */\n private static final ImmutableList REQUEST_PROCESSORS =\n ImmutableList.builder()\n .addAll(SingleFlow.REQUEST_PROCESSORS)\n .add(new AgentTransfer())\n .build();\n\n /** No additional response processors. */\n private static final ImmutableList RESPONSE_PROCESSORS = ImmutableList.of();\n\n public AutoFlow() {\n this(/* maxSteps= */ Optional.empty());\n }\n\n public AutoFlow(Optional maxSteps) {\n super(REQUEST_PROCESSORS, RESPONSE_PROCESSORS, maxSteps);\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/models/BaseLlm.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.models;\n\nimport io.reactivex.rxjava3.core.Flowable;\n\n/**\n * Abstract base class for Large Language Models (LLMs).\n *\n *

Provides a common interface for interacting with different LLMs.\n */\npublic abstract class BaseLlm {\n\n /** The name of the LLM model, e.g. gemini-1.5-flash or gemini-1.5-flash-001. */\n private final String model;\n\n public BaseLlm(String model) {\n this.model = model;\n }\n\n /**\n * Returns the name of the LLM model.\n *\n * @return The name of the LLM model.\n */\n public String model() {\n return model;\n }\n\n /**\n * Generates one content from the given LLM request and tools.\n *\n * @param llmRequest The LLM request containing the input prompt and parameters.\n * @param stream A boolean flag indicating whether to stream the response.\n * @return A Flowable of LlmResponses. For non-streaming calls, it will only yield one\n * LlmResponse. For streaming calls, it may yield more than one LlmResponse, but all yielded\n * LlmResponses should be treated as one content by merging their parts.\n */\n public abstract Flowable generateContent(LlmRequest llmRequest, boolean stream);\n\n /** Creates a live connection to the LLM. */\n public abstract BaseLlmConnection connect(LlmRequest llmRequest);\n}\n"], ["/adk-java/dev/src/main/java/com/google/adk/web/config/AdkWebCorsProperties.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.web.config;\n\nimport java.util.List;\nimport org.springframework.boot.context.properties.ConfigurationProperties;\n\n/**\n * Properties for configuring CORS in ADK Web. This class is used to load CORS settings from\n * application properties.\n */\n@ConfigurationProperties(prefix = \"adk.web.cors\")\npublic record AdkWebCorsProperties(\n String mapping,\n List origins,\n List methods,\n List headers,\n boolean allowCredentials,\n long maxAge) {\n\n public AdkWebCorsProperties {\n mapping = mapping != null ? mapping : \"/**\";\n origins = origins != null && !origins.isEmpty() ? origins : List.of();\n methods =\n methods != null && !methods.isEmpty()\n ? methods\n : List.of(\"GET\", \"POST\", \"PUT\", \"DELETE\", \"OPTIONS\");\n headers = headers != null && !headers.isEmpty() ? headers : List.of(\"*\");\n maxAge = maxAge > 0 ? maxAge : 3600;\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/models/BaseLlmConnection.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.models;\n\nimport com.google.genai.types.Blob;\nimport com.google.genai.types.Content;\nimport io.reactivex.rxjava3.core.Completable;\nimport io.reactivex.rxjava3.core.Flowable;\nimport java.util.List;\n\n/** The base class for a live model connection. */\npublic interface BaseLlmConnection {\n\n /**\n * Sends the conversation history to the model.\n *\n *

You call this method right after setting up the model connection. The model will respond if\n * the last content is from user, otherwise it will wait for new user input before responding.\n */\n Completable sendHistory(List history);\n\n /**\n * Sends a user content to the model.\n *\n *

The model will respond immediately upon receiving the content. If you send function\n * responses, all parts in the content should be function responses.\n */\n Completable sendContent(Content content);\n\n /**\n * Sends a chunk of audio or a frame of video to the model in realtime.\n *\n *

The model may not respond immediately upon receiving the blob. It will do voice activity\n * detection and decide when to respond.\n */\n Completable sendRealtime(Blob blob);\n\n /** Receives the model responses. */\n Flowable receive();\n\n /** Closes the connection. */\n void close();\n\n /** Closes the connection with an error. */\n void close(Throwable throwable);\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/LongRunningFunctionTool.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools;\n\nimport java.lang.reflect.Method;\n\n/** A function tool that returns the result asynchronously. */\npublic class LongRunningFunctionTool extends FunctionTool {\n\n public static LongRunningFunctionTool create(Method func) {\n return new LongRunningFunctionTool(func);\n }\n\n public static LongRunningFunctionTool create(Class cls, String methodName) {\n for (Method method : cls.getMethods()) {\n if (method.getName().equals(methodName)) {\n return create(method);\n }\n }\n throw new IllegalArgumentException(\n String.format(\"Method %s not found in class %s.\", methodName, cls.getName()));\n }\n\n public static LongRunningFunctionTool create(Object instance, String methodName) {\n Class cls = instance.getClass();\n for (Method method : cls.getMethods()) {\n if (method.getName().equals(methodName)) {\n return new LongRunningFunctionTool(instance, method);\n }\n }\n throw new IllegalArgumentException(\n String.format(\"Method %s not found in class %s.\", methodName, cls.getName()));\n }\n\n private LongRunningFunctionTool(Method func) {\n super(null, func, /* isLongRunning= */ true);\n }\n\n private LongRunningFunctionTool(Object instance, Method func) {\n super(instance, func, /* isLongRunning= */ true);\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/memory/SearchMemoryResponse.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.memory;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\nimport java.util.List;\n\n/** Represents the response from a memory search. */\n@AutoValue\npublic abstract class SearchMemoryResponse {\n\n /** Returns a list of memory entries that relate to the search query. */\n public abstract ImmutableList memories();\n\n /** Creates a new builder for {@link SearchMemoryResponse}. */\n public static Builder builder() {\n return new AutoValue_SearchMemoryResponse.Builder().setMemories(ImmutableList.of());\n }\n\n /** Builder for {@link SearchMemoryResponse}. */\n @AutoValue.Builder\n public abstract static class Builder {\n\n abstract Builder setMemories(ImmutableList memories);\n\n /** Sets the list of memory entries using a list. */\n public Builder setMemories(List memories) {\n return setMemories(ImmutableList.copyOf(memories));\n }\n\n /** Builds the immutable {@link SearchMemoryResponse} object. */\n public abstract SearchMemoryResponse build();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/agents/LiveRequestQueue.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.agents;\n\nimport com.google.genai.types.Blob;\nimport com.google.genai.types.Content;\nimport io.reactivex.rxjava3.core.Flowable;\nimport io.reactivex.rxjava3.processors.FlowableProcessor;\nimport io.reactivex.rxjava3.processors.MulticastProcessor;\n\n/** A queue of live requests to be sent to the model. */\npublic final class LiveRequestQueue {\n private final FlowableProcessor processor;\n\n public LiveRequestQueue() {\n MulticastProcessor processor = MulticastProcessor.create();\n processor.start();\n this.processor = processor.toSerialized();\n }\n\n public void close() {\n processor.onNext(LiveRequest.builder().close(true).build());\n processor.onComplete();\n }\n\n public void content(Content content) {\n processor.onNext(LiveRequest.builder().content(content).build());\n }\n\n public void realtime(Blob blob) {\n processor.onNext(LiveRequest.builder().blob(blob).build());\n }\n\n public void send(LiveRequest request) {\n processor.onNext(request);\n if (request.shouldClose()) {\n processor.onComplete();\n }\n }\n\n public Flowable get() {\n return processor;\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/sessions/SessionNotFoundException.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\n/** Indicates that a requested session could not be found. */\npublic class SessionNotFoundException extends SessionException {\n\n public SessionNotFoundException(String message) {\n super(message);\n }\n\n public SessionNotFoundException(String message, Throwable cause) {\n super(message, cause);\n }\n}\n"], ["/adk-java/dev/src/main/java/com/google/adk/web/config/AdkWebCorsConfig.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.web.config;\n\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.web.cors.CorsConfiguration;\nimport org.springframework.web.cors.CorsConfigurationSource;\nimport org.springframework.web.cors.UrlBasedCorsConfigurationSource;\nimport org.springframework.web.filter.CorsFilter;\n\n/**\n * Configuration class for setting up Cross-Origin Resource Sharing (CORS) in the ADK Web\n * application. This class defines beans for configuring CORS settings based on properties defined\n * in {@link AdkWebCorsProperties}.\n *\n *

CORS allows the application to handle requests from different origins, enabling secure\n * communication between the frontend and backend services.\n *\n *

Beans provided:\n *\n *

    \n *
  • {@link CorsConfigurationSource}: Configures CORS settings such as allowed origins, methods,\n * headers, credentials, and max age.\n *
  • {@link CorsFilter}: Applies the CORS configuration to incoming requests.\n *
\n */\n@Configuration\npublic class AdkWebCorsConfig {\n\n @Bean\n public CorsConfigurationSource corsConfigurationSource(AdkWebCorsProperties corsProperties) {\n CorsConfiguration configuration = new CorsConfiguration();\n\n configuration.setAllowedOrigins(corsProperties.origins());\n configuration.setAllowedMethods(corsProperties.methods());\n configuration.setAllowedHeaders(corsProperties.headers());\n configuration.setAllowCredentials(corsProperties.allowCredentials());\n configuration.setMaxAge(corsProperties.maxAge());\n\n UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();\n source.registerCorsConfiguration(corsProperties.mapping(), configuration);\n\n return source;\n }\n\n @Bean\n public CorsFilter corsFilter(CorsConfigurationSource corsConfigurationSource) {\n return new CorsFilter(corsConfigurationSource);\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/sessions/SessionException.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\n/** Represents a general error that occurred during session management operations. */\npublic class SessionException extends RuntimeException {\n\n public SessionException(String message) {\n super(message);\n }\n\n public SessionException(String message, Throwable cause) {\n super(message, cause);\n }\n\n public SessionException(Throwable cause) {\n super(cause);\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/llmflows/SingleFlow.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows.llmflows;\n\nimport com.google.common.collect.ImmutableList;\nimport java.util.List;\nimport java.util.Optional;\n\n/** Basic LLM flow with fixed request processors and no response post-processing. */\npublic class SingleFlow extends BaseLlmFlow {\n\n protected static final ImmutableList REQUEST_PROCESSORS =\n ImmutableList.of(\n new Basic(), new Instructions(), new Identity(), new Contents(), new Examples());\n\n protected static final ImmutableList RESPONSE_PROCESSORS = ImmutableList.of();\n\n public SingleFlow() {\n this(/* maxSteps= */ Optional.empty());\n }\n\n public SingleFlow(Optional maxSteps) {\n this(REQUEST_PROCESSORS, RESPONSE_PROCESSORS, maxSteps);\n }\n\n protected SingleFlow(\n List requestProcessors,\n List responseProcessors,\n Optional maxSteps) {\n super(requestProcessors, responseProcessors, maxSteps);\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/models/VertexCredentials.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.models;\n\nimport com.google.auth.oauth2.GoogleCredentials;\nimport com.google.auto.value.AutoValue;\nimport java.util.Optional;\nimport javax.annotation.Nullable;\n\n/** Credentials for accessing Gemini models through Vertex. */\n@AutoValue\npublic abstract class VertexCredentials {\n\n public abstract Optional project();\n\n public abstract Optional location();\n\n public abstract Optional credentials();\n\n public static Builder builder() {\n return new AutoValue_VertexCredentials.Builder();\n }\n\n /** Builder for {@link VertexCredentials}. */\n @AutoValue.Builder\n public abstract static class Builder {\n public abstract Builder setProject(Optional value);\n\n public abstract Builder setProject(@Nullable String value);\n\n public abstract Builder setLocation(Optional value);\n\n public abstract Builder setLocation(@Nullable String value);\n\n public abstract Builder setCredentials(Optional value);\n\n public abstract Builder setCredentials(@Nullable GoogleCredentials value);\n\n public abstract VertexCredentials build();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/utils/CollectionUtils.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.utils;\n\nimport com.google.common.collect.Iterables;\n\n/** Frequently used code snippets for collections. */\npublic final class CollectionUtils {\n\n /**\n * Checks if the given iterable is null or empty.\n *\n * @param iterable the iterable to check\n * @return true if the iterable is null or empty, false otherwise\n */\n public static boolean isNullOrEmpty(Iterable iterable) {\n return iterable == null || Iterables.isEmpty(iterable);\n }\n\n private CollectionUtils() {}\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/mcp/ConversionUtils.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools.mcp;\n\nimport com.google.adk.tools.BaseTool;\nimport com.google.genai.types.FunctionDeclaration;\nimport com.google.genai.types.Schema;\nimport io.modelcontextprotocol.spec.McpSchema;\nimport java.util.Optional;\n\n/** Utility class for converting between different representations of MCP tools. */\npublic final class ConversionUtils {\n\n public McpSchema.Tool adkToMcpToolType(BaseTool tool) {\n Optional toolDeclaration = tool.declaration();\n if (toolDeclaration.isEmpty()) {\n return new McpSchema.Tool(tool.name(), tool.description(), \"\");\n }\n Schema geminiSchema = toolDeclaration.get().parameters().get();\n return new McpSchema.Tool(tool.name(), tool.description(), geminiSchema.toJson());\n }\n\n private ConversionUtils() {}\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/artifacts/ListArtifactsResponse.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.artifacts;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\nimport java.util.List;\n\n/** Response for listing artifacts. */\n@AutoValue\npublic abstract class ListArtifactsResponse {\n\n public abstract ImmutableList filenames();\n\n /** Builder for {@link ListArtifactsResponse}. */\n @AutoValue.Builder\n public abstract static class Builder {\n public abstract Builder filenames(List filenames);\n\n public abstract ListArtifactsResponse build();\n }\n\n public static Builder builder() {\n return new AutoValue_ListArtifactsResponse.Builder();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/flows/llmflows/audio/SpeechClientInterface.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.flows.llmflows.audio;\n\nimport com.google.cloud.speech.v1.RecognitionAudio;\nimport com.google.cloud.speech.v1.RecognitionConfig;\nimport com.google.cloud.speech.v1.RecognizeResponse;\n\n/**\n * Interface for a speech-to-text client. Allows for different implementations (e.g., Cloud, Mocks).\n */\npublic interface SpeechClientInterface extends AutoCloseable {\n\n /**\n * Performs synchronous speech recognition.\n *\n * @param config The recognition configuration.\n * @param audio The audio data to transcribe.\n * @return The recognition response.\n * @throws Exception if an error occurs during recognition.\n */\n RecognizeResponse recognize(RecognitionConfig config, RecognitionAudio audio) throws Exception;\n\n /**\n * Closes the client and releases any resources.\n *\n * @throws Exception if an error occurs during closing.\n */\n @Override\n void close() throws Exception;\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/models/Model.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.models;\n\nimport com.google.auto.value.AutoValue;\nimport java.util.Optional;\n\n/** Represents a model by name or instance. */\n@AutoValue\npublic abstract class Model {\n\n public abstract Optional modelName();\n\n public abstract Optional model();\n\n public static Builder builder() {\n return new AutoValue_Model.Builder();\n }\n\n public abstract Builder toBuilder();\n\n /** Builder for {@link Model}. */\n @AutoValue.Builder\n public abstract static class Builder {\n\n public abstract Builder modelName(String modelName);\n\n public abstract Builder model(BaseLlm model);\n\n public abstract Model build();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/artifacts/ListArtifactVersionsResponse.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.artifacts;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\nimport com.google.genai.types.Part;\nimport java.util.List;\n\n/** Response for listing artifact versions. */\n@AutoValue\npublic abstract class ListArtifactVersionsResponse {\n\n public abstract ImmutableList versions();\n\n /** Builder for {@link ListArtifactVersionsResponse}. */\n @AutoValue.Builder\n public abstract static class Builder {\n public abstract Builder versions(List versions);\n\n public abstract ListArtifactVersionsResponse build();\n }\n\n public static Builder builder() {\n return new AutoValue_ListArtifactVersionsResponse.Builder();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/ToolPredicate.java", "package com.google.adk.tools;\n\nimport com.google.adk.agents.ReadonlyContext;\nimport java.util.Optional;\n\n/**\n * Functional interface to decide whether a tool should be exposed to the LLM based on the current\n * context.\n */\n@FunctionalInterface\npublic interface ToolPredicate {\n /**\n * Decides if the given tool is selected.\n *\n * @param tool The tool to check.\n * @param readonlyContext The current context.\n * @return true if the tool should be selected, false otherwise.\n */\n boolean test(BaseTool tool, Optional readonlyContext);\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/sessions/HttpApiResponse.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\nimport okhttp3.Response;\nimport okhttp3.ResponseBody;\n\n/** Wraps a real HTTP response to expose the methods needed by the GenAI SDK. */\npublic final class HttpApiResponse extends ApiResponse {\n\n private final Response response;\n\n /** Constructs a HttpApiResponse instance with the response. */\n public HttpApiResponse(Response response) {\n this.response = response;\n }\n\n /** Returns the HttpEntity from the response. */\n @Override\n public ResponseBody getResponseBody() {\n return response.body();\n }\n\n /** Closes the Http response. */\n @Override\n public void close() {\n response.close();\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/ExitLoopTool.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools;\n\n/** Exits the loop. */\npublic final class ExitLoopTool {\n public static void exitLoop(ToolContext toolContext) {\n // Exits the loop.\n // Call this function only when you are instructed to do so.\n toolContext.setActions(toolContext.actions().toBuilder().escalate(true).build());\n }\n\n private ExitLoopTool() {}\n}\n"], ["/adk-java/dev/src/main/java/com/google/adk/web/config/AgentLoadingProperties.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.web.config;\n\nimport org.springframework.boot.context.properties.ConfigurationProperties;\nimport org.springframework.stereotype.Component;\n\n/** Properties for loading agents. */\n@Component\n@ConfigurationProperties(prefix = \"adk.agents\")\npublic class AgentLoadingProperties {\n private String sourceDir = \"src/main/java\";\n private String compileClasspath;\n\n public String getSourceDir() {\n return sourceDir;\n }\n\n public void setSourceDir(String sourceDir) {\n this.sourceDir = sourceDir;\n }\n\n public String getCompileClasspath() {\n return compileClasspath;\n }\n\n public void setCompileClasspath(String compileClasspath) {\n this.compileClasspath = compileClasspath;\n }\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/mcp/McpTransportBuilder.java", "package com.google.adk.tools.mcp;\n\nimport io.modelcontextprotocol.spec.McpClientTransport;\n\n/**\n * Interface for building McpClientTransport instances. Implementations of this interface are\n * responsible for constructing concrete McpClientTransport objects based on the provided connection\n * parameters.\n */\npublic interface McpTransportBuilder {\n /**\n * Builds an McpClientTransport based on the provided connection parameters.\n *\n * @param connectionParams The parameters required to configure the transport. The type of this\n * object determines the type of transport built.\n * @return An instance of McpClientTransport.\n * @throws IllegalArgumentException if the connectionParams are not supported or invalid.\n */\n McpClientTransport build(Object connectionParams);\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/tools/Annotations.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.tools;\n\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.ElementType.PARAMETER;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\n/** Annotations for tools. */\npublic final class Annotations {\n\n /** The annotation for binding the 'Schema' input. */\n @Target({METHOD, PARAMETER})\n @Retention(RetentionPolicy.RUNTIME)\n public @interface Schema {\n String name() default \"\";\n\n String description() default \"\";\n }\n\n private Annotations() {}\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/Version.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk;\n\n/**\n * Tracks the current ADK version. Useful for tracking headers. Kept as a string literal to avoid\n * coupling with the build system.\n */\npublic final class Version {\n // Don't touch this, release-please should keep it up to date.\n public static final String JAVA_ADK_VERSION = \"0.2.1-SNAPSHOT\";\n\n private Version() {}\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/sessions/ApiResponse.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.sessions;\n\nimport okhttp3.ResponseBody;\n\n/** The API response contains a response to a call to the GenAI APIs. */\npublic abstract class ApiResponse implements AutoCloseable {\n /** Gets the HttpEntity. */\n public abstract ResponseBody getResponseBody();\n\n @Override\n public abstract void close();\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/network/ApiResponse.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.adk.network;\n\nimport okhttp3.ResponseBody;\n\n/** The API response contains a response to a call to the GenAI APIs. */\npublic abstract class ApiResponse implements AutoCloseable {\n /** Gets the ResponseBody. */\n public abstract ResponseBody getEntity();\n\n @Override\n public abstract void close();\n}\n"], ["/adk-java/core/src/main/java/com/google/adk/exceptions/LlmCallsLimitExceededException.java", "/*\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.google.adk.exceptions;\n\n/** An error indicating that the limit for calls to the LLM has been exceeded. */\npublic final class LlmCallsLimitExceededException extends Exception {\n\n public LlmCallsLimitExceededException(String message) {\n super(message);\n }\n}\n"]], "task_instance_info": {"created_time": "2025-08-20 20:39:51", "created_task_model": "DeepSeek-R1", "function_skeleton": "@Override\n public Maybe getSession (\n String appName, String userId, String sessionId, Optional configOpt) {}", "code_description": "This code segment functions to: Retrieve stored data records based on specified identifiers, apply filtering criteria to limit historical data according to configuration parameters, and combine with external state information sources before returning the processed result."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```java\n[TASK_BEGIN]\n@Override\npublic Maybe getSession(\n String appName, String userId, String sessionId, Optional configOpt) {\n Objects.requireNonNull(appName, \"appName cannot be null\");\n Objects.requireNonNull(userId, \"userId cannot be null\");\n Objects.requireNonNull(sessionId, \"sessionId cannot be null\");\n\n Session storedSession =\n sessions\n .getOrDefault(appName, new ConcurrentHashMap<>())\n .getOrDefault(userId, new ConcurrentHashMap<>())\n .get(sessionId);\n\n if (storedSession == null) {\n return Maybe.empty();\n }\n\n // Determine which data to include based on config\n boolean includeState = true;\n boolean includeEvents = true;\n if (configOpt.isPresent()) {\n GetSessionConfig config = configOpt.get();\n includeState = config.includeState();\n includeEvents = config.includeEvents();\n }\n\n // Create mutable copy with requested data\n Session.Builder builder = Session.builder(storedSession.id())\n .appName(storedSession.appName())\n .userId(storedSession.userId())\n .lastUpdateTime(storedSession.lastUpdateTime());\n\n if (includeState) {\n builder.state(new ConcurrentHashMap<>(storedSession.state()));\n } else {\n builder.state(new ConcurrentHashMap<>());\n }\n\n if (includeEvents) {\n builder.events(new ArrayList<>(storedSession.events()));\n } else {\n builder.events(new ArrayList<>());\n }\n\n Session sessionCopy = builder.build();\n\n // Merge global state only if state inclusion is enabled\n if (includeState) {\n mergeWithGlobalState(appName, userId, sessionCopy);\n }\n\n return Maybe.just(sessionCopy);\n}\n[TASK_END]\n```", "inference_time": "2025-08-20 20-41-06"}, "editdistance_info": {"edit_distance": 36.129, "calculate_time": "2025-08-20 20:41:06", "true_code_clean": "@Override\n public Maybe getSession(\n String appName, String userId, String sessionId, Optional configOpt) {\n Objects.requireNonNull(appName, \"appName cannot be null\");\n Objects.requireNonNull(userId, \"userId cannot be null\");\n Objects.requireNonNull(sessionId, \"sessionId cannot be null\");\n Objects.requireNonNull(configOpt, \"configOpt cannot be null\");\n Session storedSession =\n sessions\n .getOrDefault(appName, new ConcurrentHashMap<>())\n .getOrDefault(userId, new ConcurrentHashMap<>())\n .get(sessionId);\n if (storedSession == null) {\n return Maybe.empty();\n }\n Session sessionCopy = copySession(storedSession);\n GetSessionConfig config = configOpt.orElse(GetSessionConfig.builder().build());\n List eventsInCopy = sessionCopy.events();\n config\n .numRecentEvents()\n .ifPresent(\n num -> {\n if (!eventsInCopy.isEmpty() && num < eventsInCopy.size()) {\n List eventsToRemove = eventsInCopy.subList(0, eventsInCopy.size() - num);\n eventsToRemove.clear(); \n }\n });\n if (config.numRecentEvents().isEmpty() && config.afterTimestamp().isPresent()) {\n Instant threshold = config.afterTimestamp().get();\n eventsInCopy.removeIf(\n event -> getEventTimestampEpochSeconds(event) < threshold.getEpochSecond());\n }\n return Maybe.just(mergeWithGlobalState(appName, userId, sessionCopy));\n }", "predict_code_clean": "@Override\npublic Maybe getSession(\n String appName, String userId, String sessionId, Optional configOpt) {\n Objects.requireNonNull(appName, \"appName cannot be null\");\n Objects.requireNonNull(userId, \"userId cannot be null\");\n Objects.requireNonNull(sessionId, \"sessionId cannot be null\");\n Session storedSession =\n sessions\n .getOrDefault(appName, new ConcurrentHashMap<>())\n .getOrDefault(userId, new ConcurrentHashMap<>())\n .get(sessionId);\n if (storedSession == null) {\n return Maybe.empty();\n }\n boolean includeState = true;\n boolean includeEvents = true;\n if (configOpt.isPresent()) {\n GetSessionConfig config = configOpt.get();\n includeState = config.includeState();\n includeEvents = config.includeEvents();\n }\n Session.Builder builder = Session.builder(storedSession.id())\n .appName(storedSession.appName())\n .userId(storedSession.userId())\n .lastUpdateTime(storedSession.lastUpdateTime());\n if (includeState) {\n builder.state(new ConcurrentHashMap<>(storedSession.state()));\n } else {\n builder.state(new ConcurrentHashMap<>());\n }\n if (includeEvents) {\n builder.events(new ArrayList<>(storedSession.events()));\n } else {\n builder.events(new ArrayList<>());\n }\n Session sessionCopy = builder.build();\n if (includeState) {\n mergeWithGlobalState(appName, userId, sessionCopy);\n }\n return Maybe.just(sessionCopy);\n}"}}