Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/google/adk/utils/instructions_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,11 @@ async def _replace_match(match) -> str:
)
return ''
else:
raise KeyError(f'Context variable not found: `{var_name}`.')
logger.debug(
'Context variable %s not found in session state, returning as-is',
var_name,
)
return match.group()

return await _async_sub(r'{+[^{}]*}+', _replace_match, template)

Expand Down
26 changes: 19 additions & 7 deletions tests/unittests/utils/test_instructions_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,18 +103,30 @@ async def test_inject_session_state_with_optional_state():


@pytest.mark.asyncio
async def test_inject_session_state_with_missing_state_raises_key_error():
async def test_inject_session_state_with_missing_state_returns_literal():
instruction_template = "Hello {missing_key}!"
invocation_context = await _create_test_readonly_context(
state={"user_name": "Foo"}
)

with pytest.raises(
KeyError, match="Context variable not found: `missing_key`."
):
await instructions_utils.inject_session_state(
instruction_template, invocation_context
)
populated_instruction = await instructions_utils.inject_session_state(
instruction_template, invocation_context
)
assert populated_instruction == "Hello {missing_key}!"


@pytest.mark.asyncio
async def test_inject_session_state_preserves_literal_identifier_patterns():
"""Literal {identifier} patterns in docs/tool descriptions should not crash."""
instruction_template = (
"The formatString supports interpolation via {expression} syntax."
)
invocation_context = await _create_test_readonly_context()

populated_instruction = await instructions_utils.inject_session_state(
instruction_template, invocation_context
)
assert populated_instruction == instruction_template


@pytest.mark.asyncio
Expand Down
Loading