|
| 1 | +# Copyright 2026 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""A before_tool_callback that gates tool calls on a classifier's answer.""" |
| 16 | + |
| 17 | +from __future__ import annotations |
| 18 | + |
| 19 | +from collections.abc import Awaitable |
| 20 | +from collections.abc import Callable |
| 21 | +import logging |
| 22 | +from typing import Any |
| 23 | +from typing import Literal |
| 24 | + |
| 25 | +from google.adk.labs.classifiers import BaseClassifier |
| 26 | +from google.adk.labs.classifiers import Binary |
| 27 | +from google.adk.labs.classifiers import BinaryAnswer |
| 28 | +from google.adk.labs.classifiers import ClassifierInput |
| 29 | +from google.adk.labs.classifiers import JSONContent |
| 30 | +from google.adk.tools.base_tool import BaseTool |
| 31 | +from google.adk.tools.tool_context import ToolContext |
| 32 | + |
| 33 | +logger = logging.getLogger("google_adk." + __name__) |
| 34 | + |
| 35 | +StateExtractor = Callable[ |
| 36 | + [BaseTool, dict[str, Any], ToolContext], ClassifierInput |
| 37 | +] |
| 38 | +ToolGateCallback = Callable[ |
| 39 | + [BaseTool, dict[str, Any], ToolContext], Awaitable[dict[str, Any] | None] |
| 40 | +] |
| 41 | + |
| 42 | + |
| 43 | +def _default_state( |
| 44 | + tool: BaseTool, args: dict[str, Any], tool_context: ToolContext |
| 45 | +) -> ClassifierInput: |
| 46 | + del tool_context # Unused. |
| 47 | + return {"tool": tool.name, "description": tool.description, "args": args} |
| 48 | + |
| 49 | + |
| 50 | +def create_tool_gate_callback( |
| 51 | + *, |
| 52 | + classifier: BaseClassifier, |
| 53 | + instructions: JSONContent, |
| 54 | + criteria: JSONContent | None = None, |
| 55 | + threshold: float = 0.5, |
| 56 | + on_threshold_exceeded: Literal["block", "confirm"] = "block", |
| 57 | + state_extractor: StateExtractor | None = None, |
| 58 | +) -> ToolGateCallback: |
| 59 | + """Creates a before_tool_callback that asks a classifier if a call is risky. |
| 60 | +
|
| 61 | + Before each tool call, the callback asks `classifier` a `Binary` question |
| 62 | + about the call. If the probability of true is at or above `threshold`, the |
| 63 | + call is blocked, or held until the user confirms it. |
| 64 | +
|
| 65 | + Args: |
| 66 | + classifier: Any `BaseClassifier`, such as `LlmClassifier` or a dedicated |
| 67 | + decision model. |
| 68 | + instructions: The yes/no question to ask about each call, where yes means |
| 69 | + the call is risky. |
| 70 | + criteria: Optionally, a description of what counts as risky. |
| 71 | + threshold: The probability of risky at or above which the gate acts. |
| 72 | + on_threshold_exceeded: "block" skips the call and returns an error to the |
| 73 | + model. "confirm" asks the user through `tool_context.request_confirmation` |
| 74 | + and runs the call only if they approve. |
| 75 | + state_extractor: Builds the classifier input from the tool, its arguments |
| 76 | + and the tool context. Defaults to the tool's name, description and |
| 77 | + arguments. |
| 78 | +
|
| 79 | + Returns: |
| 80 | + An async callback to pass as an agent's `before_tool_callback`. |
| 81 | + """ |
| 82 | + if not 0.0 <= threshold <= 1.0: |
| 83 | + raise ValueError(f"threshold must be in [0, 1], got {threshold}.") |
| 84 | + if on_threshold_exceeded not in ("block", "confirm"): |
| 85 | + raise ValueError( |
| 86 | + "on_threshold_exceeded must be 'block' or 'confirm', got" |
| 87 | + f" {on_threshold_exceeded!r}." |
| 88 | + ) |
| 89 | + question = Binary(instructions=instructions, criteria=criteria) |
| 90 | + extract_state = state_extractor or _default_state |
| 91 | + |
| 92 | + async def tool_gate( |
| 93 | + tool: BaseTool, args: dict[str, Any], tool_context: ToolContext |
| 94 | + ) -> dict[str, Any] | None: |
| 95 | + # A confirmed call comes back through this callback with the user's |
| 96 | + # answer attached; classifying it again could ask the user twice. |
| 97 | + confirmation = tool_context.tool_confirmation |
| 98 | + if confirmation is not None: |
| 99 | + if confirmation.confirmed: |
| 100 | + return None |
| 101 | + return {"error": f"The user rejected this call to {tool.name}."} |
| 102 | + |
| 103 | + try: |
| 104 | + response = await classifier.classify( |
| 105 | + input=extract_state(tool, args, tool_context), |
| 106 | + questions={"risky": question}, |
| 107 | + ) |
| 108 | + answer = response.answers["risky"] |
| 109 | + if not isinstance(answer, BinaryAnswer): |
| 110 | + raise ValueError(f"Expected a BinaryAnswer, got {answer!r}.") |
| 111 | + probability = answer.probability |
| 112 | + except Exception: # pylint: disable=broad-exception-caught |
| 113 | + # Fail closed: a classifier outage must not let risky calls through. |
| 114 | + logger.exception("Tool gate classifier failed for %s.", tool.name) |
| 115 | + probability = 1.0 |
| 116 | + |
| 117 | + logger.info("Tool gate: %s risk=%.2f", tool.name, probability) |
| 118 | + if probability < threshold: |
| 119 | + return None |
| 120 | + |
| 121 | + if on_threshold_exceeded == "confirm": |
| 122 | + tool_context.request_confirmation( |
| 123 | + hint=( |
| 124 | + f"The tool gate flagged this call to {tool.name} as risky" |
| 125 | + f" ({probability:.0%}). Approve it?" |
| 126 | + ), |
| 127 | + ) |
| 128 | + # Pause for the user instead of letting the model react to the error, |
| 129 | + # which would make it call the tool again. |
| 130 | + tool_context.actions.skip_summarization = True |
| 131 | + return { |
| 132 | + "error": ( |
| 133 | + "This tool call requires confirmation, please approve or reject." |
| 134 | + ) |
| 135 | + } |
| 136 | + return { |
| 137 | + "error": ( |
| 138 | + f"The call to {tool.name} was blocked because it was classified" |
| 139 | + " as risky. Do not retry it; tell the user it was blocked." |
| 140 | + ) |
| 141 | + } |
| 142 | + |
| 143 | + return tool_gate |
0 commit comments