Skip to content

Commit ec54bd4

Browse files
GWealecopybara-github
authored andcommitted
perf(utils): cache find_context_parameter introspection
Adds @functools.lru_cache to find_context_parameter so the inspect.signature + typing.get_type_hints lookup runs once per function, not on every MCP confirmation callback or declaration build. No public surface change. Co-authored-by: George Weale <gweale@google.com> PiperOrigin-RevId: 916204929
1 parent 2388090 commit ec54bd4

2 files changed

Lines changed: 26 additions & 0 deletions

File tree

src/google/adk/utils/context_utils.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
from __future__ import annotations
2222

2323
from contextlib import aclosing
24+
import functools
2425
import inspect
2526
import typing
2627
from typing import Any
@@ -62,6 +63,7 @@ def _is_context_type(annotation: Any) -> bool:
6263
return annotation is Context
6364

6465

66+
@functools.lru_cache(maxsize=1024)
6567
def find_context_parameter(func: Callable[..., Any]) -> str | None:
6668
"""Find the parameter name that has a Context type annotation.
6769

tests/unittests/utils/test_context_utils.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,12 @@
1515
"""Tests for context_utils module."""
1616

1717
from typing import Optional
18+
from unittest import mock
1819

1920
from google.adk.agents.callback_context import CallbackContext
2021
from google.adk.agents.context import Context
2122
from google.adk.tools.tool_context import ToolContext
23+
from google.adk.utils import context_utils
2224
from google.adk.utils.context_utils import find_context_parameter
2325

2426

@@ -129,3 +131,25 @@ def my_tool(
129131
return query
130132

131133
assert find_context_parameter(my_tool) == 'ctx'
134+
135+
136+
class TestFindContextParameterCaching:
137+
"""Tests for find_context_parameter caching behavior."""
138+
139+
def test_repeated_calls_inspect_signature_once(self):
140+
"""Repeated calls with the same function reuse the cached result."""
141+
142+
def my_tool(ctx: Context) -> str:
143+
return 'ok'
144+
145+
find_context_parameter.cache_clear()
146+
147+
with mock.patch.object(
148+
context_utils.inspect,
149+
'signature',
150+
wraps=context_utils.inspect.signature,
151+
) as spy:
152+
for _ in range(10):
153+
assert find_context_parameter(my_tool) == 'ctx'
154+
155+
assert spy.call_count == 1

0 commit comments

Comments
 (0)