diff --git a/src/google/adk/cli/utils/state.py b/src/google/adk/cli/utils/state.py index eb012a980da..f8d260048bc 100644 --- a/src/google/adk/cli/utils/state.py +++ b/src/google/adk/cli/utils/state.py @@ -14,11 +14,12 @@ from __future__ import annotations -import re from typing import Any from typing import TYPE_CHECKING from ...agents.llm_agent import LlmAgent +from ...flows.llm_flows.prompt._instructions_utils import _is_valid_state_name +from ...flows.llm_flows.prompt._instructions_utils import _TEMPLATE_VAR_PATTERN if TYPE_CHECKING: from ...agents.base_agent import BaseAgent @@ -46,8 +47,14 @@ def _create_empty_state( and agent.instruction and isinstance(agent.instruction, str) ): - for key in re.findall(r'{([\w]+)}', agent.instruction): - all_state[key] = '' + for match in _TEMPLATE_VAR_PATTERN.finditer(agent.instruction): + var_name = match.group().lstrip('{').rstrip('}').strip() + if var_name.endswith('?'): + continue + if not var_name.startswith('artifact.') and _is_valid_state_name( + var_name + ): + all_state[var_name] = '' # `agent` is typed `BaseAgent | BaseNode` rather than just `BaseNode` (which diff --git a/tests/unittests/cli/utils/test_state.py b/tests/unittests/cli/utils/test_state.py index afd5e9514a6..939c3a9961c 100644 --- a/tests/unittests/cli/utils/test_state.py +++ b/tests/unittests/cli/utils/test_state.py @@ -100,6 +100,23 @@ def test_create_empty_state_returns_empty_dict_when_nothing_to_seed(): assert create_empty_state(LlmAgent(name='root', instruction='no slots')) == {} +def test_create_empty_state_seeds_prefixed_and_whitespace_placeholders(): + agent = LlmAgent( + name='root', + instruction=( + 'User {user:name}, app {app:mode}, temp {temp:draft}, ' + 'padded { topic }, optional {opt?}, artifact {artifact.doc}.' + ), + ) + + assert create_empty_state(agent) == { + 'user:name': '', + 'app:mode': '', + 'temp:draft': '', + 'topic': '', + } + + def test_create_empty_state_reads_agent_tree(): child = LlmAgent(name='child', instruction='Use {child_key}') root = LlmAgent(