From 8a933669a04d263e46b165b008b138b49d751256 Mon Sep 17 00:00:00 2001 From: WastingTimeToThink <1061195831@qq.com> Date: Tue, 26 Aug 2025 22:55:33 +0800 Subject: [PATCH 1/8] feat(tools): enforce built-in tools limitations at build/start with helpful errors - Add BuiltInTool marker interface. - Add ToolConstraints to validate agent tree: (A1) only one built-in tool per agent; cannot mix with others (A2) built-ins forbidden in sub-agents - Hook validation at LlmAgent.Builder#build() - Unit tests for 5 scenarios; helpful error messages with docs link. --- .../java/com/google/adk/agents/LlmAgent.java | 6 +- .../com/google/adk/tools/BuiltInTool.java | 19 +++ .../adk/tools/internal/ToolConstraints.java | 152 ++++++++++++++++++ .../tools/internal/ToolConstraintsTest.java | 86 ++++++++++ 4 files changed, 262 insertions(+), 1 deletion(-) create mode 100644 core/src/main/java/com/google/adk/tools/BuiltInTool.java create mode 100644 core/src/main/java/com/google/adk/tools/internal/ToolConstraints.java create mode 100644 core/src/test/java/com/google/adk/tools/internal/ToolConstraintsTest.java diff --git a/core/src/main/java/com/google/adk/agents/LlmAgent.java b/core/src/main/java/com/google/adk/agents/LlmAgent.java index d1be4c09dc..b508d47d04 100644 --- a/core/src/main/java/com/google/adk/agents/LlmAgent.java +++ b/core/src/main/java/com/google/adk/agents/LlmAgent.java @@ -56,6 +56,7 @@ import com.google.adk.tools.BaseTool.ToolConfig; import com.google.adk.tools.BaseToolset; import com.google.adk.utils.ComponentRegistry; +import com.google.adk.tools.internal.ToolConstraints; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.errorprone.annotations.CanIgnoreReturnValue; @@ -614,7 +615,10 @@ protected void validate() { public LlmAgent build() { validate(); - return new LlmAgent(this); + LlmAgent built = new LlmAgent(this); + // Newly added built-in tool verification + ToolConstraints.validateAgentTree(built); + return built; } } diff --git a/core/src/main/java/com/google/adk/tools/BuiltInTool.java b/core/src/main/java/com/google/adk/tools/BuiltInTool.java new file mode 100644 index 0000000000..5e9149f724 --- /dev/null +++ b/core/src/main/java/com/google/adk/tools/BuiltInTool.java @@ -0,0 +1,19 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.google.adk.tools; + +/** Marker interface for built-in (special) tools with framework-level constraints. */ +public interface BuiltInTool {} diff --git a/core/src/main/java/com/google/adk/tools/internal/ToolConstraints.java b/core/src/main/java/com/google/adk/tools/internal/ToolConstraints.java new file mode 100644 index 0000000000..635b0e5697 --- /dev/null +++ b/core/src/main/java/com/google/adk/tools/internal/ToolConstraints.java @@ -0,0 +1,152 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.google.adk.tools.internal; + +import com.google.adk.agents.BaseAgent; +import com.google.adk.agents.LlmAgent; +import com.google.adk.tools.BuiltInTool; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +/** Guardrails for built-in tools usage. */ +public final class ToolConstraints { + + private static final String DOC = + "See docs: https://google.github.io/adk-docs/tools/built-in-tools/#limitations"; + + private ToolConstraints() {} + + /** Public entry: validate the whole agent subtree. */ + public static void validateAgentTree(BaseAgent agent) { + Objects.requireNonNull(agent, "agent"); + if (!(agent instanceof LlmAgent llm)) { + // 仅针对 LlmAgent 的工具组合做校验 + return; + } + validateSingleAgent(llm); + for (BaseAgent child : subAgentsCompat(llm)) { + validateAgentTree(child); + } + } + + /** Validate constraints on a single LlmAgent. */ + private static void validateSingleAgent(LlmAgent agent) { + List tools = new ArrayList<>(declaredToolsCompat(agent)); + + long builtinCount = tools.stream().filter(t -> t instanceof BuiltInTool).count(); + boolean hasBuiltin = builtinCount > 0; + boolean hasOthers = tools.stream().anyMatch(t -> !(t instanceof BuiltInTool)); + + // A1: Only one built-in tool is allowed in a single Agent, and it cannot coexist with other + // tools. + if (builtinCount > 1 || (hasBuiltin && hasOthers)) { + throw new IllegalStateException(errorMixedBuiltins(agent.name(), tools)); + } + + // A2: Subagents are not allowed to use built-in tools + if (hasBuiltin && parentAgentCompat(agent) != null) { + throw new IllegalStateException(errorBuiltinInSubAgent(agent.name())); + } + } + + // ---------- Friendly error messages ---------- + + private static String errorMixedBuiltins(String agentName, List tools) { + String toolNames = + tools.stream() + .map(t -> t == null ? "null" : t.getClass().getSimpleName()) + .collect(Collectors.joining(", ")); + return "[Built-in tools limitation violated] Agent `" + + agentName + + "` has invalid tool mix: " + + toolNames + + ". Only one built-in tool allowed, and it cannot be used with other tools. " + + DOC; + } + + private static String errorBuiltinInSubAgent(String agentName) { + return "[Built-in tools limitation violated] Sub-agent `" + + agentName + + "` cannot use a built-in tool. Built-ins must be used only at the root/single agent. " + + DOC; + } + + // ---------- Compatibility helpers (avoid hard-coding method names) ---------- + + /** Return the declared tools list using best-effort method discovery. */ + @SuppressWarnings("unchecked") + private static List declaredToolsCompat(LlmAgent agent) { + // Priority:tools() → declaredTools() → getTools() + for (String m : new String[] {"tools", "declaredTools", "getTools"}) { + try { + var mh = + MethodHandles.publicLookup() + .findVirtual(agent.getClass(), m, MethodType.methodType(List.class)); + Object result = mh.invoke(agent); + if (result instanceof List) { + return new ArrayList<>((List) result); + } + } catch (Throwable ignore) { + // try next + } + } + // Returns empty if not found + return Collections.emptyList(); + } + + /** Return sub agents using best-effort method discovery. */ + @SuppressWarnings("unchecked") + private static List subAgentsCompat(LlmAgent agent) { + for (String m : new String[] {"subAgents", "children", "getSubAgents"}) { + try { + var mh = + MethodHandles.publicLookup() + .findVirtual(agent.getClass(), m, MethodType.methodType(List.class)); + Object result = mh.invoke(agent); + if (result instanceof List) { + List raw = (List) result; + List safe = + raw.stream().filter(e -> e instanceof BaseAgent).map(e -> (BaseAgent) e).toList(); + return new ArrayList<>(safe); + } + } catch (Throwable ignore) { + // try next + } + } + return Collections.emptyList(); + } + + /** Return parent agent if available. */ + private static BaseAgent parentAgentCompat(LlmAgent agent) { + for (String m : new String[] {"parentAgent", "getParent", "getParentAgent"}) { + try { + var mh = + MethodHandles.publicLookup() + .findVirtual(agent.getClass(), m, MethodType.methodType(BaseAgent.class)); + Object result = mh.invoke(agent); + return (result instanceof BaseAgent) ? (BaseAgent) result : null; + } catch (Throwable ignore) { + // try next + } + } + return null; + } +} diff --git a/core/src/test/java/com/google/adk/tools/internal/ToolConstraintsTest.java b/core/src/test/java/com/google/adk/tools/internal/ToolConstraintsTest.java new file mode 100644 index 0000000000..d7a8127a9f --- /dev/null +++ b/core/src/test/java/com/google/adk/tools/internal/ToolConstraintsTest.java @@ -0,0 +1,86 @@ +/* + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.adk.tools.internal; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +import com.google.adk.agents.BaseAgent; +import com.google.adk.agents.LlmAgent; +import com.google.adk.tools.BuiltInTool; +import java.util.List; +import org.junit.jupiter.api.Test; + +/** Unit tests for ToolConstraints guardrails (pure white-box, no BaseTool dependency). */ +final class ToolConstraintsTest { + + // only rely on the BuiltInTool marker interface to distinguish whether it is built-in + static final class FakeBuiltinTool implements BuiltInTool {} + + static final class FakeNormalTool {} + + @SuppressWarnings("unchecked") + private static LlmAgent mockAgent( + String name, BaseAgent parent, List tools, List subs) { + + LlmAgent a = mock(LlmAgent.class); + + when(a.name()).thenReturn(name); + + when(a.parentAgent()).thenReturn(parent); + when(a.subAgents()).thenReturn((List) subs); + when(a.tools()).thenReturn((List) tools); + + return a; + } + + @Test + void singleBuiltin_only_passes() { + LlmAgent root = mockAgent("root", null, List.of(new FakeBuiltinTool()), List.of()); + assertDoesNotThrow(() -> ToolConstraints.validateAgentTree(root)); + } + + @Test + void builtin_plus_normal_throws() { + LlmAgent root = + mockAgent("root", null, List.of(new FakeBuiltinTool(), new FakeNormalTool()), List.of()); + assertThrows(IllegalStateException.class, () -> ToolConstraints.validateAgentTree(root)); + } + + @Test + void two_builtins_throws() { + LlmAgent root = + mockAgent("root", null, List.of(new FakeBuiltinTool(), new FakeBuiltinTool()), List.of()); + assertThrows(IllegalStateException.class, () -> ToolConstraints.validateAgentTree(root)); + } + + @Test + void builtin_in_subAgent_throws() { + LlmAgent child = + mockAgent("child", mock(LlmAgent.class), List.of(new FakeBuiltinTool()), List.of()); + LlmAgent root = mockAgent("root", null, List.of(new FakeNormalTool()), List.of(child)); + assertThrows(IllegalStateException.class, () -> ToolConstraints.validateAgentTree(root)); + } + + @Test + void only_normal_tools_in_tree_passes() { + LlmAgent child = + mockAgent("child", mock(LlmAgent.class), List.of(new FakeNormalTool()), List.of()); + LlmAgent root = mockAgent("root", null, List.of(new FakeNormalTool()), List.of(child)); + assertDoesNotThrow(() -> ToolConstraints.validateAgentTree(root)); + } +} From d028edb56720e380d5733f62cb977c1c5371496c Mon Sep 17 00:00:00 2001 From: SHICHEN ZHANG <110387451+WastingTimeToThink@users.noreply.github.com> Date: Wed, 27 Aug 2025 01:01:52 +0800 Subject: [PATCH 2/8] Update core/src/main/java/com/google/adk/tools/internal/ToolConstraints.java Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com> --- .../java/com/google/adk/tools/internal/ToolConstraints.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/src/main/java/com/google/adk/tools/internal/ToolConstraints.java b/core/src/main/java/com/google/adk/tools/internal/ToolConstraints.java index 635b0e5697..128ba83a20 100644 --- a/core/src/main/java/com/google/adk/tools/internal/ToolConstraints.java +++ b/core/src/main/java/com/google/adk/tools/internal/ToolConstraints.java @@ -38,7 +38,7 @@ private ToolConstraints() {} public static void validateAgentTree(BaseAgent agent) { Objects.requireNonNull(agent, "agent"); if (!(agent instanceof LlmAgent llm)) { - // 仅针对 LlmAgent 的工具组合做校验 + // Only validate tool combinations for LlmAgent return; } validateSingleAgent(llm); From df84e9763661d3da65d649872a0dd53904633cad Mon Sep 17 00:00:00 2001 From: SHICHEN ZHANG <110387451+WastingTimeToThink@users.noreply.github.com> Date: Wed, 27 Aug 2025 01:01:59 +0800 Subject: [PATCH 3/8] Update core/src/main/java/com/google/adk/tools/internal/ToolConstraints.java Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com> --- .../java/com/google/adk/tools/internal/ToolConstraints.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/src/main/java/com/google/adk/tools/internal/ToolConstraints.java b/core/src/main/java/com/google/adk/tools/internal/ToolConstraints.java index 128ba83a20..c4eeceab7a 100644 --- a/core/src/main/java/com/google/adk/tools/internal/ToolConstraints.java +++ b/core/src/main/java/com/google/adk/tools/internal/ToolConstraints.java @@ -49,7 +49,7 @@ public static void validateAgentTree(BaseAgent agent) { /** Validate constraints on a single LlmAgent. */ private static void validateSingleAgent(LlmAgent agent) { - List tools = new ArrayList<>(declaredToolsCompat(agent)); + List tools = declaredToolsCompat(agent); long builtinCount = tools.stream().filter(t -> t instanceof BuiltInTool).count(); boolean hasBuiltin = builtinCount > 0; From d4ee944ab7dc77790fc563bc4f72c485fd502d6a Mon Sep 17 00:00:00 2001 From: SHICHEN ZHANG <110387451+WastingTimeToThink@users.noreply.github.com> Date: Wed, 27 Aug 2025 01:02:06 +0800 Subject: [PATCH 4/8] Update core/src/main/java/com/google/adk/tools/internal/ToolConstraints.java Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com> --- .../java/com/google/adk/tools/internal/ToolConstraints.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/src/main/java/com/google/adk/tools/internal/ToolConstraints.java b/core/src/main/java/com/google/adk/tools/internal/ToolConstraints.java index c4eeceab7a..fec64ef90e 100644 --- a/core/src/main/java/com/google/adk/tools/internal/ToolConstraints.java +++ b/core/src/main/java/com/google/adk/tools/internal/ToolConstraints.java @@ -94,7 +94,7 @@ private static String errorBuiltinInSubAgent(String agentName) { /** Return the declared tools list using best-effort method discovery. */ @SuppressWarnings("unchecked") private static List declaredToolsCompat(LlmAgent agent) { - // Priority:tools() → declaredTools() → getTools() + // Priority: tools() → declaredTools() → getTools() for (String m : new String[] {"tools", "declaredTools", "getTools"}) { try { var mh = From 9ddbbd218629909940ef640f1a1187b306d683af Mon Sep 17 00:00:00 2001 From: SHICHEN ZHANG <110387451+WastingTimeToThink@users.noreply.github.com> Date: Wed, 27 Aug 2025 01:02:12 +0800 Subject: [PATCH 5/8] Update core/src/main/java/com/google/adk/tools/internal/ToolConstraints.java Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com> --- .../java/com/google/adk/tools/internal/ToolConstraints.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/core/src/main/java/com/google/adk/tools/internal/ToolConstraints.java b/core/src/main/java/com/google/adk/tools/internal/ToolConstraints.java index fec64ef90e..ec32b13d08 100644 --- a/core/src/main/java/com/google/adk/tools/internal/ToolConstraints.java +++ b/core/src/main/java/com/google/adk/tools/internal/ToolConstraints.java @@ -123,9 +123,7 @@ private static List subAgentsCompat(LlmAgent agent) { Object result = mh.invoke(agent); if (result instanceof List) { List raw = (List) result; - List safe = - raw.stream().filter(e -> e instanceof BaseAgent).map(e -> (BaseAgent) e).toList(); - return new ArrayList<>(safe); + return raw.stream().filter(e -> e instanceof BaseAgent).map(e -> (BaseAgent) e).toList(); } } catch (Throwable ignore) { // try next From a51eed9e0d747637010cca620220f40667d78aa5 Mon Sep 17 00:00:00 2001 From: WastingTimeToThink <1061195831@qq.com> Date: Wed, 27 Aug 2025 11:14:39 +0800 Subject: [PATCH 6/8] WIP: local changes before rebase --- .../java/com/google/adk/agents/LlmAgent.java | 315 +++++++++++++++++- 1 file changed, 311 insertions(+), 4 deletions(-) diff --git a/core/src/main/java/com/google/adk/agents/LlmAgent.java b/core/src/main/java/com/google/adk/agents/LlmAgent.java index b508d47d04..45a7f6f907 100644 --- a/core/src/main/java/com/google/adk/agents/LlmAgent.java +++ b/core/src/main/java/com/google/adk/agents/LlmAgent.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.google.adk.agents; import static com.google.common.base.Strings.isNullOrEmpty; @@ -54,6 +53,7 @@ import com.google.adk.tools.BaseTool; import com.google.adk.tools.BaseTool.ToolArgsConfig; import com.google.adk.tools.BaseTool.ToolConfig; +import com.google.adk.tools.BaseTool.ToolConfig; import com.google.adk.tools.BaseToolset; import com.google.adk.utils.ComponentRegistry; import com.google.adk.tools.internal.ToolConstraints; @@ -614,10 +614,14 @@ protected void validate() { } public LlmAgent build() { - validate(); LlmAgent built = new LlmAgent(this); - // Newly added built-in tool verification - ToolConstraints.validateAgentTree(built); + // New Guardrail Check + if (Boolean.getBoolean("adk.enableToolConstraints")) { + try { + ToolConstraints.validateAgentTree(built); + } catch (NullPointerException ignored) { + } + } return built; } } @@ -1187,4 +1191,307 @@ static BaseTool resolveInstanceViaReflection(String toolName) throws Exception { } return null; } + + /** + * Creates an LlmAgent from configuration. + * + * @param config the agent configuration + * @param configAbsPath The absolute path to the agent config file. This is needed for resolving + * relative paths for e.g. tools. + * @return the configured LlmAgent + * @throws ConfigurationException if the configuration is invalid + *

TODO: Config agent features are not yet ready for public use. + */ + public static LlmAgent fromConfig(LlmAgentConfig config, String configAbsPath) + throws ConfigurationException { + logger.debug("Creating LlmAgent from config: {}", config.name()); + + // Validate required fields + if (config.name() == null || config.name().trim().isEmpty()) { + throw new ConfigurationException("Agent name is required"); + } + + if (config.instruction() == null || config.instruction().trim().isEmpty()) { + throw new ConfigurationException("Agent instruction is required"); + } + + // Create builder with required fields + Builder builder = + LlmAgent.builder() + .name(config.name()) + .description(nullToEmpty(config.description())) + .instruction(config.instruction()); + + if (config.model() != null && !config.model().trim().isEmpty()) { + builder.model(config.model()); + } + + try { + if (config.tools() != null) { + builder.tools(resolveTools(config.tools(), configAbsPath)); + } + } catch (ConfigurationException e) { + throw new ConfigurationException("Error resolving tools for agent " + config.name(), e); + } + + // Set optional transfer configuration + if (config.disallowTransferToParent() != null) { + builder.disallowTransferToParent(config.disallowTransferToParent()); + } + + if (config.disallowTransferToPeers() != null) { + builder.disallowTransferToPeers(config.disallowTransferToPeers()); + } + + // Set optional output key + if (config.outputKey() != null && !config.outputKey().trim().isEmpty()) { + builder.outputKey(config.outputKey()); + } + + // Build and return the agent + LlmAgent agent = builder.build(); + logger.info("Successfully created LlmAgent: {}", agent.name()); + + return agent; + } + + /** + * Resolves a list of tool configurations into {@link BaseTool} instances. + * + *

This method is only for use by Agent Development Kit. + * + * @param toolConfigs The list of tool configurations to resolve. + * @param configAbsPath The absolute path to the agent config file currently being processed. This + * path can be used to resolve relative paths for tool configurations, if necessary. + * @return An immutable list of resolved {@link BaseTool} instances. + * @throws ConfigurationException if any tool configuration is invalid (e.g., missing name), if a + * tool cannot be found by its name or class, or if tool instantiation fails. + */ + static ImmutableList resolveTools(List toolConfigs, String configAbsPath) + throws ConfigurationException { + + if (toolConfigs == null || toolConfigs.isEmpty()) { + return ImmutableList.of(); + } + + ImmutableList.Builder resolvedTools = ImmutableList.builder(); + + for (ToolConfig toolConfig : toolConfigs) { + try { + if (isNullOrEmpty(toolConfig.name())) { + throw new ConfigurationException("Tool name cannot be empty"); + } + + String toolName = toolConfig.name().trim(); + + // Option 1: Try to resolve as a tool instance + BaseTool tool = resolveToolInstance(toolName); + if (tool != null) { + resolvedTools.add(tool); + logger.debug("Successfully resolved tool instance: {}", toolName); + continue; + } + + // Option 2: Try to resolve as a tool class (with or without args) + BaseTool toolFromClass = resolveToolFromClass(toolName, toolConfig.args()); + if (toolFromClass != null) { + resolvedTools.add(toolFromClass); + logger.debug("Successfully resolved tool from class: {}", toolName); + continue; + } + + throw new ConfigurationException("Tool not found: " + toolName); + + } catch (Exception e) { + String errorMsg = "Failed to resolve tool: " + toolConfig.name(); + logger.error(errorMsg, e); + throw new ConfigurationException(errorMsg, e); + } + } + + return resolvedTools.build(); + } + + /** + * Resolves a tool instance by its unique name or its static field reference. + * + *

It first checks the {@link ComponentRegistry} for a registered tool instance. If not found, + * and the name looks like a fully qualified Java name referencing a static field (e.g., + * "com.google.mytools.MyToolClass.INSTANCE"), it attempts to resolve it via reflection using + * {@link #resolveInstanceViaReflection(String)}. + * + * @param toolName The name of the tool or a static field reference (e.g., "myTool", + * "com.google.mytools.MyToolClass.INSTANCE"). + * @return The resolved tool instance, or {@code null} if the tool is not found in the registry + * and cannot be resolved via reflection. + */ + @Nullable + static BaseTool resolveToolInstance(String toolName) { + ComponentRegistry registry = ComponentRegistry.getInstance(); + + // First try registry + Optional toolOpt = ComponentRegistry.resolveToolInstance(toolName); + if (toolOpt.isPresent()) { + return toolOpt.get(); + } + + // If not in registry and looks like Java qualified name, try reflection + if (isJavaQualifiedName(toolName)) { + try { + BaseTool tool = resolveInstanceViaReflection(toolName); + if (tool != null) { + registry.register(toolName, tool); + logger.debug("Resolved and registered tool instance via reflection: {}", toolName); + return tool; + } + } catch (Exception e) { + logger.debug("Failed to resolve instance via reflection: {}", toolName, e); + } + } + logger.debug("Could not resolve tool instance: {}", toolName); + return null; + } + + /** + * Resolves a tool from a class name and optional arguments. + * + *

It attempts to load the class specified by {@code className}. If {@code args} are provided + * and non-empty, it looks for a static factory method {@code fromConfig(ToolArgsConfig)} on the + * class to instantiate the tool. If {@code args} are null or empty, it looks for a default + * constructor. + * + * @param className The fully qualified name of the tool class to instantiate. + * @param args Optional configuration arguments for tool creation. If provided, the class must + * implement a static {@code fromConfig(ToolArgsConfig)} factory method. If null or empty, the + * class must have a default constructor. + * @return The instantiated tool instance, or {@code null} if the class cannot be found or loaded. + * @throws ConfigurationException if {@code args} are provided but no {@code fromConfig} method + * exists, if {@code args} are not provided but no default constructor exists, or if + * instantiation via the factory method or constructor fails. + */ + @Nullable + static BaseTool resolveToolFromClass(String className, ToolArgsConfig args) + throws ConfigurationException { + ComponentRegistry registry = ComponentRegistry.getInstance(); + + // First try registry for class + Optional> classOpt = ComponentRegistry.resolveToolClass(className); + Class toolClass = null; + + if (classOpt.isPresent()) { + toolClass = classOpt.get(); + } else if (isJavaQualifiedName(className)) { + // Try reflection to get class + try { + Class clazz = Thread.currentThread().getContextClassLoader().loadClass(className); + if (BaseTool.class.isAssignableFrom(clazz)) { + toolClass = clazz.asSubclass(BaseTool.class); + // Optimization: register for reuse + registry.register(className, toolClass); + logger.debug("Resolved and registered tool class via reflection: {}", className); + } + } catch (ClassNotFoundException e) { + logger.debug("Failed to resolve class via reflection: {}", className, e); + return null; + } + } + + if (toolClass == null) { + return null; + } + + // If args provided and not empty, try fromConfig method first + if (args != null && !args.isEmpty()) { + try { + Method fromConfigMethod = toolClass.getMethod("fromConfig", ToolArgsConfig.class); + Object instance = fromConfigMethod.invoke(null, args); + if (instance instanceof BaseTool baseTool) { + return baseTool; + } + } catch (NoSuchMethodException e) { + throw new ConfigurationException( + "Class " + className + " does not have fromConfig method but args were provided.", e); + } catch (Exception e) { + logger.error("Error calling fromConfig on class {}", className, e); + throw new ConfigurationException("Error creating tool from class " + className, e); + } + } + + // No args provided or empty args, try default constructor + try { + Constructor constructor = toolClass.getDeclaredConstructor(); + constructor.setAccessible(true); + return constructor.newInstance(); + } catch (NoSuchMethodException e) { + throw new ConfigurationException( + "Class " + className + " does not have a default constructor and no args were provided.", + e); + } catch (Exception e) { + logger.error("Error calling default constructor on class {}", className, e); + throw new ConfigurationException( + "Error creating tool from class " + className + " using default constructor", e); + } + } + + /** + * Checks if a string appears to be a Java fully qualified name, such as "com.google.adk.MyClass" + * or "com.google.adk.MyClass.MY_FIELD". + * + *

It verifies that the name contains at least one dot ('.') and consists of characters valid + * for Java identifiers and package names. + * + * @param name The string to check. + * @return {@code true} if the string matches the pattern of a Java qualified name, {@code false} + * otherwise. + */ + static boolean isJavaQualifiedName(String name) { + if (name == null || name.trim().isEmpty()) { + return false; + } + return name.contains(".") && name.matches("^[a-zA-Z_$][a-zA-Z0-9_.$]*$"); + } + + /** + * Resolves a {@link BaseTool} instance by attempting to access a public static field via + * reflection. + * + *

This method expects {@code toolName} to be in the format + * "com.google.package.ClassName.STATIC_FIELD_NAME", where "STATIC_FIELD_NAME" is the name of a + * public static field in "com.google.package.ClassName" that holds a {@link BaseTool} instance. + * + * @param toolName The fully qualified name of a static field holding a tool instance. + * @return The {@link BaseTool} instance, or {@code null} if {@code toolName} is not in the + * expected format, or if the field is not found, not static, or not of type {@link BaseTool}. + * @throws Exception if the class specified in {@code toolName} cannot be loaded, or if there is a + * security manager preventing reflection, or if accessing the field causes an exception. + */ + @Nullable + static BaseTool resolveInstanceViaReflection(String toolName) throws Exception { + int lastDotIndex = toolName.lastIndexOf('.'); + if (lastDotIndex == -1) { + return null; + } + + String className = toolName.substring(0, lastDotIndex); + String fieldName = toolName.substring(lastDotIndex + 1); + + Class clazz = Thread.currentThread().getContextClassLoader().loadClass(className); + + try { + Field field = clazz.getField(fieldName); + if (!Modifier.isStatic(field.getModifiers())) { + logger.debug("Field {} in class {} is not static", fieldName, className); + return null; + } + Object instance = field.get(null); + if (instance instanceof BaseTool baseTool) { + return baseTool; + } else { + logger.debug("Field {} in class {} is not a BaseTool instance", fieldName, className); + } + } catch (NoSuchFieldException e) { + logger.debug("Field {} not found in class {}", fieldName, className); + } + return null; + } } From 867433f12d0889bdd6381fbc44b91cba04ae617b Mon Sep 17 00:00:00 2001 From: WastingTimeToThink <1061195831@qq.com> Date: Wed, 27 Aug 2025 11:31:24 +0800 Subject: [PATCH 7/8] WIP: local changes --- core/src/main/java/com/google/adk/agents/LlmAgent.java | 1 - 1 file changed, 1 deletion(-) diff --git a/core/src/main/java/com/google/adk/agents/LlmAgent.java b/core/src/main/java/com/google/adk/agents/LlmAgent.java index 45a7f6f907..bae9f75d25 100644 --- a/core/src/main/java/com/google/adk/agents/LlmAgent.java +++ b/core/src/main/java/com/google/adk/agents/LlmAgent.java @@ -53,7 +53,6 @@ import com.google.adk.tools.BaseTool; import com.google.adk.tools.BaseTool.ToolArgsConfig; import com.google.adk.tools.BaseTool.ToolConfig; -import com.google.adk.tools.BaseTool.ToolConfig; import com.google.adk.tools.BaseToolset; import com.google.adk.utils.ComponentRegistry; import com.google.adk.tools.internal.ToolConstraints; From 18dc8adf0e3a4f32be380a4ed42764ba95b54222 Mon Sep 17 00:00:00 2001 From: WastingTimeToThink <1061195831@qq.com> Date: Wed, 27 Aug 2025 12:24:43 +0800 Subject: [PATCH 8/8] fix confilct --- .../java/com/google/adk/agents/LlmAgent.java | 314 +----------------- 1 file changed, 3 insertions(+), 311 deletions(-) diff --git a/core/src/main/java/com/google/adk/agents/LlmAgent.java b/core/src/main/java/com/google/adk/agents/LlmAgent.java index bae9f75d25..c38f91777c 100644 --- a/core/src/main/java/com/google/adk/agents/LlmAgent.java +++ b/core/src/main/java/com/google/adk/agents/LlmAgent.java @@ -54,8 +54,8 @@ import com.google.adk.tools.BaseTool.ToolArgsConfig; import com.google.adk.tools.BaseTool.ToolConfig; import com.google.adk.tools.BaseToolset; -import com.google.adk.utils.ComponentRegistry; import com.google.adk.tools.internal.ToolConstraints; +import com.google.adk.utils.ComponentRegistry; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.errorprone.annotations.CanIgnoreReturnValue; @@ -613,14 +613,9 @@ protected void validate() { } public LlmAgent build() { + validate(); LlmAgent built = new LlmAgent(this); - // New Guardrail Check - if (Boolean.getBoolean("adk.enableToolConstraints")) { - try { - ToolConstraints.validateAgentTree(built); - } catch (NullPointerException ignored) { - } - } + ToolConstraints.validateAgentTree(built); return built; } } @@ -1190,307 +1185,4 @@ static BaseTool resolveInstanceViaReflection(String toolName) throws Exception { } return null; } - - /** - * Creates an LlmAgent from configuration. - * - * @param config the agent configuration - * @param configAbsPath The absolute path to the agent config file. This is needed for resolving - * relative paths for e.g. tools. - * @return the configured LlmAgent - * @throws ConfigurationException if the configuration is invalid - *

TODO: Config agent features are not yet ready for public use. - */ - public static LlmAgent fromConfig(LlmAgentConfig config, String configAbsPath) - throws ConfigurationException { - logger.debug("Creating LlmAgent from config: {}", config.name()); - - // Validate required fields - if (config.name() == null || config.name().trim().isEmpty()) { - throw new ConfigurationException("Agent name is required"); - } - - if (config.instruction() == null || config.instruction().trim().isEmpty()) { - throw new ConfigurationException("Agent instruction is required"); - } - - // Create builder with required fields - Builder builder = - LlmAgent.builder() - .name(config.name()) - .description(nullToEmpty(config.description())) - .instruction(config.instruction()); - - if (config.model() != null && !config.model().trim().isEmpty()) { - builder.model(config.model()); - } - - try { - if (config.tools() != null) { - builder.tools(resolveTools(config.tools(), configAbsPath)); - } - } catch (ConfigurationException e) { - throw new ConfigurationException("Error resolving tools for agent " + config.name(), e); - } - - // Set optional transfer configuration - if (config.disallowTransferToParent() != null) { - builder.disallowTransferToParent(config.disallowTransferToParent()); - } - - if (config.disallowTransferToPeers() != null) { - builder.disallowTransferToPeers(config.disallowTransferToPeers()); - } - - // Set optional output key - if (config.outputKey() != null && !config.outputKey().trim().isEmpty()) { - builder.outputKey(config.outputKey()); - } - - // Build and return the agent - LlmAgent agent = builder.build(); - logger.info("Successfully created LlmAgent: {}", agent.name()); - - return agent; - } - - /** - * Resolves a list of tool configurations into {@link BaseTool} instances. - * - *

This method is only for use by Agent Development Kit. - * - * @param toolConfigs The list of tool configurations to resolve. - * @param configAbsPath The absolute path to the agent config file currently being processed. This - * path can be used to resolve relative paths for tool configurations, if necessary. - * @return An immutable list of resolved {@link BaseTool} instances. - * @throws ConfigurationException if any tool configuration is invalid (e.g., missing name), if a - * tool cannot be found by its name or class, or if tool instantiation fails. - */ - static ImmutableList resolveTools(List toolConfigs, String configAbsPath) - throws ConfigurationException { - - if (toolConfigs == null || toolConfigs.isEmpty()) { - return ImmutableList.of(); - } - - ImmutableList.Builder resolvedTools = ImmutableList.builder(); - - for (ToolConfig toolConfig : toolConfigs) { - try { - if (isNullOrEmpty(toolConfig.name())) { - throw new ConfigurationException("Tool name cannot be empty"); - } - - String toolName = toolConfig.name().trim(); - - // Option 1: Try to resolve as a tool instance - BaseTool tool = resolveToolInstance(toolName); - if (tool != null) { - resolvedTools.add(tool); - logger.debug("Successfully resolved tool instance: {}", toolName); - continue; - } - - // Option 2: Try to resolve as a tool class (with or without args) - BaseTool toolFromClass = resolveToolFromClass(toolName, toolConfig.args()); - if (toolFromClass != null) { - resolvedTools.add(toolFromClass); - logger.debug("Successfully resolved tool from class: {}", toolName); - continue; - } - - throw new ConfigurationException("Tool not found: " + toolName); - - } catch (Exception e) { - String errorMsg = "Failed to resolve tool: " + toolConfig.name(); - logger.error(errorMsg, e); - throw new ConfigurationException(errorMsg, e); - } - } - - return resolvedTools.build(); - } - - /** - * Resolves a tool instance by its unique name or its static field reference. - * - *

It first checks the {@link ComponentRegistry} for a registered tool instance. If not found, - * and the name looks like a fully qualified Java name referencing a static field (e.g., - * "com.google.mytools.MyToolClass.INSTANCE"), it attempts to resolve it via reflection using - * {@link #resolveInstanceViaReflection(String)}. - * - * @param toolName The name of the tool or a static field reference (e.g., "myTool", - * "com.google.mytools.MyToolClass.INSTANCE"). - * @return The resolved tool instance, or {@code null} if the tool is not found in the registry - * and cannot be resolved via reflection. - */ - @Nullable - static BaseTool resolveToolInstance(String toolName) { - ComponentRegistry registry = ComponentRegistry.getInstance(); - - // First try registry - Optional toolOpt = ComponentRegistry.resolveToolInstance(toolName); - if (toolOpt.isPresent()) { - return toolOpt.get(); - } - - // If not in registry and looks like Java qualified name, try reflection - if (isJavaQualifiedName(toolName)) { - try { - BaseTool tool = resolveInstanceViaReflection(toolName); - if (tool != null) { - registry.register(toolName, tool); - logger.debug("Resolved and registered tool instance via reflection: {}", toolName); - return tool; - } - } catch (Exception e) { - logger.debug("Failed to resolve instance via reflection: {}", toolName, e); - } - } - logger.debug("Could not resolve tool instance: {}", toolName); - return null; - } - - /** - * Resolves a tool from a class name and optional arguments. - * - *

It attempts to load the class specified by {@code className}. If {@code args} are provided - * and non-empty, it looks for a static factory method {@code fromConfig(ToolArgsConfig)} on the - * class to instantiate the tool. If {@code args} are null or empty, it looks for a default - * constructor. - * - * @param className The fully qualified name of the tool class to instantiate. - * @param args Optional configuration arguments for tool creation. If provided, the class must - * implement a static {@code fromConfig(ToolArgsConfig)} factory method. If null or empty, the - * class must have a default constructor. - * @return The instantiated tool instance, or {@code null} if the class cannot be found or loaded. - * @throws ConfigurationException if {@code args} are provided but no {@code fromConfig} method - * exists, if {@code args} are not provided but no default constructor exists, or if - * instantiation via the factory method or constructor fails. - */ - @Nullable - static BaseTool resolveToolFromClass(String className, ToolArgsConfig args) - throws ConfigurationException { - ComponentRegistry registry = ComponentRegistry.getInstance(); - - // First try registry for class - Optional> classOpt = ComponentRegistry.resolveToolClass(className); - Class toolClass = null; - - if (classOpt.isPresent()) { - toolClass = classOpt.get(); - } else if (isJavaQualifiedName(className)) { - // Try reflection to get class - try { - Class clazz = Thread.currentThread().getContextClassLoader().loadClass(className); - if (BaseTool.class.isAssignableFrom(clazz)) { - toolClass = clazz.asSubclass(BaseTool.class); - // Optimization: register for reuse - registry.register(className, toolClass); - logger.debug("Resolved and registered tool class via reflection: {}", className); - } - } catch (ClassNotFoundException e) { - logger.debug("Failed to resolve class via reflection: {}", className, e); - return null; - } - } - - if (toolClass == null) { - return null; - } - - // If args provided and not empty, try fromConfig method first - if (args != null && !args.isEmpty()) { - try { - Method fromConfigMethod = toolClass.getMethod("fromConfig", ToolArgsConfig.class); - Object instance = fromConfigMethod.invoke(null, args); - if (instance instanceof BaseTool baseTool) { - return baseTool; - } - } catch (NoSuchMethodException e) { - throw new ConfigurationException( - "Class " + className + " does not have fromConfig method but args were provided.", e); - } catch (Exception e) { - logger.error("Error calling fromConfig on class {}", className, e); - throw new ConfigurationException("Error creating tool from class " + className, e); - } - } - - // No args provided or empty args, try default constructor - try { - Constructor constructor = toolClass.getDeclaredConstructor(); - constructor.setAccessible(true); - return constructor.newInstance(); - } catch (NoSuchMethodException e) { - throw new ConfigurationException( - "Class " + className + " does not have a default constructor and no args were provided.", - e); - } catch (Exception e) { - logger.error("Error calling default constructor on class {}", className, e); - throw new ConfigurationException( - "Error creating tool from class " + className + " using default constructor", e); - } - } - - /** - * Checks if a string appears to be a Java fully qualified name, such as "com.google.adk.MyClass" - * or "com.google.adk.MyClass.MY_FIELD". - * - *

It verifies that the name contains at least one dot ('.') and consists of characters valid - * for Java identifiers and package names. - * - * @param name The string to check. - * @return {@code true} if the string matches the pattern of a Java qualified name, {@code false} - * otherwise. - */ - static boolean isJavaQualifiedName(String name) { - if (name == null || name.trim().isEmpty()) { - return false; - } - return name.contains(".") && name.matches("^[a-zA-Z_$][a-zA-Z0-9_.$]*$"); - } - - /** - * Resolves a {@link BaseTool} instance by attempting to access a public static field via - * reflection. - * - *

This method expects {@code toolName} to be in the format - * "com.google.package.ClassName.STATIC_FIELD_NAME", where "STATIC_FIELD_NAME" is the name of a - * public static field in "com.google.package.ClassName" that holds a {@link BaseTool} instance. - * - * @param toolName The fully qualified name of a static field holding a tool instance. - * @return The {@link BaseTool} instance, or {@code null} if {@code toolName} is not in the - * expected format, or if the field is not found, not static, or not of type {@link BaseTool}. - * @throws Exception if the class specified in {@code toolName} cannot be loaded, or if there is a - * security manager preventing reflection, or if accessing the field causes an exception. - */ - @Nullable - static BaseTool resolveInstanceViaReflection(String toolName) throws Exception { - int lastDotIndex = toolName.lastIndexOf('.'); - if (lastDotIndex == -1) { - return null; - } - - String className = toolName.substring(0, lastDotIndex); - String fieldName = toolName.substring(lastDotIndex + 1); - - Class clazz = Thread.currentThread().getContextClassLoader().loadClass(className); - - try { - Field field = clazz.getField(fieldName); - if (!Modifier.isStatic(field.getModifiers())) { - logger.debug("Field {} in class {} is not static", fieldName, className); - return null; - } - Object instance = field.get(null); - if (instance instanceof BaseTool baseTool) { - return baseTool; - } else { - logger.debug("Field {} in class {} is not a BaseTool instance", fieldName, className); - } - } catch (NoSuchFieldException e) { - logger.debug("Field {} not found in class {}", fieldName, className); - } - return null; - } }