-
Notifications
You must be signed in to change notification settings - Fork 58
feat(adk): pass telemetry attributes through toolbox-adk #720
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -14,7 +14,7 @@ | |
|
|
||
| import inspect | ||
| import logging | ||
| from typing import Any, Awaitable, Callable, Dict, Mapping, Optional | ||
| from typing import Any, Awaitable, Callable, Dict, Mapping, Optional, Union, cast | ||
|
|
||
| import toolbox_core | ||
| from fastapi.openapi.models import OAuth2, OAuthFlowAuthorizationCode, OAuthFlows | ||
|
|
@@ -27,7 +27,11 @@ | |
| from google.adk.tools.base_tool import BaseTool | ||
| from google.adk.tools.tool_context import ToolContext | ||
| from google.genai.types import FunctionDeclaration, Schema, Type | ||
| from toolbox_core.protocol import AdditionalPropertiesSchema, ParameterSchema | ||
| from toolbox_core.protocol import ( | ||
| AdditionalPropertiesSchema, | ||
| ParameterSchema, | ||
| TelemetryAttributes, | ||
| ) | ||
| from toolbox_core.tool import ToolboxTool as CoreToolboxTool | ||
| from typing_extensions import override | ||
|
|
||
|
|
@@ -45,12 +49,26 @@ def __init__( | |
| core_tool: CoreToolboxTool, | ||
| auth_config: Optional[CredentialConfig] = None, | ||
| adk_token_getters: Optional[Mapping[str, Any]] = None, | ||
| telemetry_attributes: Optional[ | ||
| Union[ | ||
| TelemetryAttributes, | ||
| Callable[[], TelemetryAttributes], | ||
| Callable[[ToolContext], TelemetryAttributes], | ||
| Callable[[], Awaitable[TelemetryAttributes]], | ||
| Callable[[ToolContext], Awaitable[TelemetryAttributes]], | ||
| ] | ||
| ] = None, | ||
| ): | ||
| """ | ||
| Args: | ||
| core_tool: The underlying toolbox_core.py tool instance. | ||
| auth_config: Credential configuration to handle interactive flows. | ||
| adk_token_getters: Tool-specific auth token getters. | ||
| telemetry_attributes: Telemetry attributes (model, user id, agent | ||
| id) sent to the server with each invocation. Either a static | ||
| TelemetryAttributes instance, or a callable resolved on every | ||
| invocation; callables taking one argument receive the live | ||
| ToolContext, mirroring the auth token getter pattern. | ||
| """ | ||
| # We act as a proxy. | ||
| # We need to extract metadata from the core tool to satisfy BaseTool's contract. | ||
|
|
@@ -74,6 +92,7 @@ def __init__( | |
| self._core_tool = core_tool | ||
| self._auth_config = auth_config | ||
| self._adk_token_getters = adk_token_getters or {} | ||
| self._telemetry_attributes = telemetry_attributes | ||
|
|
||
| def _param_type_to_schema_type(self, param_type: str) -> Type: | ||
| type_map = { | ||
|
|
@@ -288,8 +307,20 @@ async def run_async( | |
| error: Optional[Exception] = None | ||
|
|
||
| try: | ||
| # Resolve telemetry attributes onto a per-invocation copy of the | ||
| # core tool. Unlike the auth getters above, this must not be | ||
| # assigned back to self._core_tool: attributes resolved from one | ||
| # ToolContext (e.g. a user id) would otherwise persist and leak | ||
| # into later invocations served by this same tool instance. | ||
| core_tool = self._core_tool | ||
| telemetry_attributes = await self._resolve_telemetry_attributes( | ||
| tool_context | ||
| ) | ||
| if telemetry_attributes is not None: | ||
| core_tool = core_tool.add_telemetry_attributes(telemetry_attributes) | ||
|
|
||
| # Execute the core tool | ||
| result = await self._core_tool(**args) | ||
| result = await core_tool(**args) | ||
| return result | ||
|
|
||
| except Exception as e: | ||
|
|
@@ -299,6 +330,61 @@ async def run_async( | |
| if reset_token: | ||
| USER_TOKEN_CONTEXT_VAR.reset(reset_token) | ||
|
|
||
| async def _resolve_telemetry_attributes( | ||
| self, tool_context: ToolContext | ||
| ) -> Optional[TelemetryAttributes]: | ||
| """Resolves the configured telemetry attributes for one invocation. | ||
|
|
||
| Static instances are returned as-is. Callables are invoked on every | ||
| call; 1-arity callables receive the live tool_context (same arity | ||
| sniffing as adk_token_getters) and may be sync or async. | ||
| """ | ||
| attributes = self._telemetry_attributes | ||
| if attributes is None or isinstance(attributes, TelemetryAttributes): | ||
| return attributes | ||
|
|
||
| sig = inspect.signature(attributes) | ||
| if self._accepts_tool_context_arg(sig, tool_context): | ||
| context_getter = cast( | ||
| Union[ | ||
| Callable[[ToolContext], TelemetryAttributes], | ||
| Callable[[ToolContext], Awaitable[TelemetryAttributes]], | ||
| ], | ||
| attributes, | ||
| ) | ||
| resolved = context_getter(tool_context) | ||
| else: | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. optional: Is it by any chance still possible to pass a function with default arguments? def get_telemetry(ctx: ToolContext, default_model: str = "gemini-3.5-flash") -> TelemetryAttributes:
return TelemetryAttributes(llm_model=default_model, ...)If so then If it makes sense then should we also determine whether the function can accept 1 positional argument by checking parameter kinds and required parameters, or by inspecting positional parameters? |
||
| no_arg_getter = cast( | ||
| Union[ | ||
| Callable[[], TelemetryAttributes], | ||
| Callable[[], Awaitable[TelemetryAttributes]], | ||
| ], | ||
| attributes, | ||
| ) | ||
| resolved = no_arg_getter() | ||
| if inspect.isawaitable(resolved): | ||
| resolved = await resolved | ||
| return self._validate_resolved_telemetry_attributes(resolved) | ||
|
|
||
| def _validate_resolved_telemetry_attributes( | ||
| self, resolved: Any | ||
| ) -> Optional[TelemetryAttributes]: | ||
| if resolved is None or isinstance(resolved, TelemetryAttributes): | ||
| return resolved | ||
| raise TypeError( | ||
| "telemetry_attributes callable must return TelemetryAttributes or None" | ||
| ) | ||
|
|
||
| def _accepts_tool_context_arg( | ||
| self, sig: inspect.Signature, tool_context: ToolContext | ||
| ) -> bool: | ||
| """Returns whether a callable signature can receive ToolContext.""" | ||
| try: | ||
| sig.bind(tool_context) | ||
| return True | ||
| except TypeError: | ||
| return False | ||
|
|
||
| def bind_params(self, bounded_params: Dict[str, Any]) -> "ToolboxTool": | ||
| """Allows runtime binding of parameters, delegating to core tool.""" | ||
| new_core_tool = self._core_tool.bind_params(bounded_params) | ||
|
|
@@ -307,4 +393,5 @@ def bind_params(self, bounded_params: Dict[str, Any]) -> "ToolboxTool": | |
| core_tool=new_core_tool, | ||
| auth_config=self._auth_config, | ||
| adk_token_getters=self._adk_token_getters, | ||
| telemetry_attributes=self._telemetry_attributes, | ||
| ) | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -18,6 +18,7 @@ | |
| from google.adk.tools.base_tool import BaseTool | ||
| from google.adk.tools.base_toolset import BaseToolset | ||
| from google.adk.tools.tool_context import ToolContext | ||
| from toolbox_core.protocol import TelemetryAttributes | ||
| from toolbox_core.utils import validate_unused_requirements | ||
| from typing_extensions import override | ||
|
|
||
|
|
@@ -52,6 +53,15 @@ def __init__( | |
| ], | ||
| ] | ||
| ] = None, | ||
| telemetry_attributes: Optional[ | ||
| Union[ | ||
| TelemetryAttributes, | ||
| Callable[[], TelemetryAttributes], | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. optional: Curious what if the callable wants to resolve a |
||
| Callable[[ToolContext], TelemetryAttributes], | ||
| Callable[[], Awaitable[TelemetryAttributes]], | ||
| Callable[[ToolContext], Awaitable[TelemetryAttributes]], | ||
| ] | ||
| ] = None, | ||
| **kwargs: Any, | ||
| ): | ||
| """ | ||
|
|
@@ -63,6 +73,11 @@ def __init__( | |
| additional_headers: Extra headers (static or dynamic). | ||
| bound_params: Parameters to bind globally to loaded tools. | ||
| auth_token_getters: Mapping of auth service names to token getters. | ||
| telemetry_attributes: Telemetry attributes (model, user id, agent | ||
| id) sent to the server with each tool invocation. Either a | ||
| static TelemetryAttributes instance, or a callable resolved on | ||
| every invocation; callables taking one argument receive the | ||
| live ToolContext. | ||
| """ | ||
| super().__init__() | ||
| self.__server_url = server_url | ||
|
|
@@ -75,6 +90,7 @@ def __init__( | |
| self.__tool_names = tool_names | ||
| self.__bound_params = bound_params | ||
| self.__auth_token_getters = auth_token_getters | ||
| self.__telemetry_attributes = telemetry_attributes | ||
|
|
||
| @property | ||
| def client(self) -> ToolboxClient: | ||
|
|
@@ -151,6 +167,7 @@ async def get_tools( | |
| core_tool=t, | ||
| auth_config=self.client.credential_config, | ||
| adk_token_getters=self.__auth_token_getters, | ||
| telemetry_attributes=self.__telemetry_attributes, | ||
| ) | ||
| for t in tools | ||
| ] | ||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.