diff --git a/src/google/adk/utils/instructions_utils.py b/src/google/adk/utils/instructions_utils.py index 54b18f96..e47c0dd5 100644 --- a/src/google/adk/utils/instructions_utils.py +++ b/src/google/adk/utils/instructions_utils.py @@ -181,24 +181,29 @@ async def inject_session_state( if leading_count == trailing_count: n = leading_count + is_valid = _is_valid_path(full_path) or full_path.startswith('artifact.') if n % 2 == 0: # Even: Escaped, no evaluation - half_n = n // 2 - return '{' * half_n + full_path + '}' * half_n + if is_valid: + half_n = n // 2 + return '{' * half_n + full_path + '}' * half_n + else: + return raw_match else: # Odd: Evaluate and wrap - if not _is_valid_path(full_path) and not full_path.startswith('artifact.'): + if not is_valid: return raw_match evaluated_value = await _evaluate_path(full_path) wrap_braces = (n - 1) // 2 return '{' * wrap_braces + evaluated_value + '}' * wrap_braces else: # Asymmetric: fallback to old behavior (treat as N=1 if valid path) - if not _is_valid_path(full_path) and not full_path.startswith('artifact.'): + if not _is_valid_path(full_path) and not full_path.startswith( + 'artifact.' + ): return raw_match return await _evaluate_path(full_path) - return await _async_sub(r'{+[^{}]*}+', _replace_match, template) diff --git a/tests/unittests/utils/test_instructions_utils.py b/tests/unittests/utils/test_instructions_utils.py index 7f8f86b9..9327ab4f 100644 --- a/tests/unittests/utils/test_instructions_utils.py +++ b/tests/unittests/utils/test_instructions_utils.py @@ -516,14 +516,19 @@ async def test_inject_session_state_with_invalid_nested_path_returns_original(): @pytest.mark.asyncio async def test_inject_session_state_escaped_braces(): - instruction_template = "This is a literal {{placeholder}} and this is {value}." + instruction_template = ( + "This is a literal {{placeholder}} and this is {value}." + ) invocation_context = await _create_test_readonly_context( state={"value": "real_value"} ) populated_instruction = await instructions_utils.inject_session_state( instruction_template, invocation_context ) - assert populated_instruction == "This is a literal {placeholder} and this is real_value." + assert ( + populated_instruction + == "This is a literal {placeholder} and this is real_value." + ) @pytest.mark.asyncio @@ -556,7 +561,9 @@ async def test_inject_session_state_quadruple_braces(): populated_instruction = await instructions_utils.inject_session_state( instruction_template, invocation_context ) - assert populated_instruction == "This is literal double braces: {{placeholder}}." + assert ( + populated_instruction == "This is literal double braces: {{placeholder}}." + ) @pytest.mark.asyncio @@ -581,4 +588,3 @@ async def test_inject_session_state_asymmetric_braces_right(): instruction_template, invocation_context ) assert populated_instruction == "Asymmetric right: real_value." -