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
27 changes: 27 additions & 0 deletions src/google/adk/cli/api_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -2329,6 +2329,31 @@ def _set_telemetry_context_if_needed(runner: Runner) -> None:
else:
_is_visual_builder.set(False)

def _require_replay_plugin_for_recorded_responses(
runner: Runner, state_delta: Optional[dict[str, Any]]
) -> None:
"""Reject recorded tool replay before a run if its plugin is absent."""
config = (state_delta or {}).get("_adk_replay_config")
if not isinstance(config, dict) or not config.get(
"replay_tool_responses"
):
return

from .plugins.replay_plugin import ReplayPlugin

if not any(
isinstance(plugin, ReplayPlugin)
for plugin in runner.plugin_manager.plugins
):
raise HTTPException(
status_code=400,
detail=(
"Recorded tool responses require ReplayPlugin. Start the"
" server with --extra_plugins"
" google.adk.cli.plugins.replay_plugin.ReplayPlugin."
),
)

@app.post(
"/run", response_model=list[Event], response_model_exclude_none=True
)
Expand All @@ -2342,6 +2367,7 @@ async def run_agent(req: RunAgentRequest, request: Request) -> Response:
req.app_name = app_name
self.current_app_name_ref.value = req.app_name
runner = await self.get_runner_async(req.app_name)
_require_replay_plugin_for_recorded_responses(runner, req.state_delta)
_set_telemetry_context_if_needed(runner)
run_config = None
if (
Expand Down Expand Up @@ -2440,6 +2466,7 @@ async def run_agent_sse(
self.current_app_name_ref.value = req.app_name
stream_mode = StreamingMode.SSE if req.streaming else StreamingMode.NONE
runner = await self.get_runner_async(req.app_name)
_require_replay_plugin_for_recorded_responses(runner, req.state_delta)
_set_telemetry_context_if_needed(runner)

# Build the run config before the response starts. Constructing it
Expand Down
6 changes: 6 additions & 0 deletions src/google/adk/cli/conformance/adk_web_server_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,7 @@ async def run_agent(
mode: Optional[Literal["record", "replay"]] = None,
test_case_dir: Optional[str] = None,
user_message_index: Optional[int] = None,
replay_tool_responses: Optional[dict[str, list[str]]] = None,
) -> AsyncGenerator[Event, None]:
"""Run an agent with streaming Server-Sent Events response.

Expand All @@ -243,6 +244,7 @@ async def run_agent(
mode: Optional conformance mode ("record" or "replay") to trigger recording
test_case_dir: Optional test case directory path for conformance recording
user_message_index: Optional user message index for conformance recording
replay_tool_responses: Agent tools that use recorded responses during replay

Yields:
Event objects streamed from the agent execution
Expand Down Expand Up @@ -271,6 +273,10 @@ async def run_agent(
"dir": str(test_case_dir),
"user_message_index": user_message_index,
}
if mode == "replay" and replay_tool_responses:
request.state_delta["_adk_replay_config"][
"replay_tool_responses"
] = replay_tool_responses
if request.streaming:
request.state_delta["_adk_replay_config"]["streaming_mode"] = "sse"
else:
Expand Down
18 changes: 17 additions & 1 deletion src/google/adk/cli/conformance/cli_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,7 @@ async def _run_user_messages(
mode="replay",
test_case_dir=str(test_case.dir),
user_message_index=user_message_index,
replay_tool_responses=test_case.test_spec.replay_tool_responses,
):
if getattr(event, "partial", False):
continue
Expand Down Expand Up @@ -308,7 +309,22 @@ async def run_all_tests(self) -> _ConformanceTestSummary:

results: list[_TestResult] = []
for test_case in test_cases:
click.echo(f"Running {test_case.category}/{test_case.name}...", nl=False)
replayed_tools = [
f"{agent_name}.{tool_name}"
for agent_name, tool_names in (
test_case.test_spec.replay_tool_responses.items()
)
for tool_name in tool_names
]
replay_detail = (
f" (recorded tool responses: {', '.join(replayed_tools)})"
if self.mode == "replay" and replayed_tools
else ""
)
click.echo(
f"Running {test_case.category}/{test_case.name}{replay_detail}...",
nl=False,
)
if self.mode == "replay":
result = await self._run_test_case_replay(test_case)
else:
Expand Down
3 changes: 3 additions & 0 deletions src/google/adk/cli/conformance/test_case.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,9 @@ class TestSpec(BaseModel):
initial_state: dict[str, Any] = Field(default_factory=dict)
"""The initial state key-value pairs in the creation_session request."""

replay_tool_responses: dict[str, list[str]] = Field(default_factory=dict)
"""Agent names and tools that use recorded responses during replay."""

user_messages: list[UserMessage] = Field(default_factory=list)
"""Sequence of user messages to send to the agent during test execution."""

Expand Down
39 changes: 39 additions & 0 deletions src/google/adk/cli/plugins/replay_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

from __future__ import annotations

from copy import deepcopy
import logging
from pathlib import Path
from typing import Any
Expand Down Expand Up @@ -59,6 +60,7 @@ class _InvocationReplayState(BaseModel):
test_case_path: str
user_message_index: int
recordings: Recordings
replay_tool_responses: dict[str, list[str]] = Field(default_factory=dict)

# Per-agent replay indices for parallel execution
# key: agent_name -> current tool replay index for that agent
Expand Down Expand Up @@ -112,6 +114,24 @@ async def before_tool_callback(

from google.adk.tools.agent_tool import AgentTool

use_recorded_response = tool.name in state.replay_tool_responses.get(
agent_name, ()
)
if use_recorded_response:
if isinstance(tool, AgentTool):
raise ReplayConfigError(
"Recorded response replay is not supported for AgentTool"
f" '{tool.name}'."
)
if (
recording.tool_response is None
or recording.tool_response.response is None
):
raise ReplayVerificationError(
f"Tool recording for agent '{agent_name}' has no tool_response."
)
return deepcopy(recording.tool_response.response)

if not isinstance(tool, AgentTool):
# TODO: support replay requests and responses from AgentTool.
await tool.run_async(args=tool_args, tool_context=tool_context)
Expand Down Expand Up @@ -207,7 +227,26 @@ def _load_invocation_state(
test_case_path=case_dir,
user_message_index=msg_index,
recordings=recordings,
replay_tool_responses=config.get("replay_tool_responses", {}),
)
recorded_tools = {
(recording.agent_name, recording.tool_recording.tool_call.name)
for recording in recordings.recordings
if recording.tool_recording and recording.tool_recording.tool_call
}
unknown_tools = {
(agent_name, tool_name)
for agent_name, tool_names in state.replay_tool_responses.items()
for tool_name in tool_names
} - recorded_tools
if unknown_tools:
raise ReplayConfigError(
"Recorded response replay selected tools absent from recordings: "
+ ", ".join(
f"{agent_name}.{tool_name}"
for agent_name, tool_name in sorted(unknown_tools)
)
)
self._invocation_states[invocation_id] = state
logger.debug(
"Loaded replay state for invocation %s: case_dir=%s, msg_index=%s, "
Expand Down
53 changes: 53 additions & 0 deletions tests/unittests/cli/conformance/test_adk_web_server_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,59 @@ def mock_stream(*_args, **_kwargs):
assert events[1].invocation_id == "test_invocation_2"


@pytest.mark.parametrize("streaming_mode", [False, True])
async def test_replay_tool_selection_is_sent_to_server(streaming_mode):
"""Replay selection reaches the server in the per-turn state delta."""
client = AdkWebServerClient()
sent_requests = []

class EmptyStreamResponse:

def raise_for_status(self):
pass

async def aiter_lines(self):
if False:
yield "data:"

async def __aenter__(self):
return self

async def __aexit__(self, exc_type, exc_val, exc_tb):
pass

def mock_stream(*_args, **kwargs):
sent_requests.append(kwargs["json"])
return EmptyStreamResponse()

with patch("httpx.AsyncClient") as mock_client_class:
mock_client = AsyncMock()
mock_client.stream = mock_stream
mock_client_class.return_value = mock_client
request = RunAgentRequest(
app_name="app",
user_id="user",
session_id="session",
streaming=streaming_mode,
)

async for _ in client.run_agent(
request,
mode="replay",
test_case_dir="case",
user_message_index=0,
replay_tool_responses={"agent_a": ["send_notice"]},
):
pass

assert sent_requests[0]["stateDelta"]["_adk_replay_config"] == {
"dir": "case",
"user_message_index": 0,
"streaming_mode": "sse" if streaming_mode else "none",
"replay_tool_responses": {"agent_a": ["send_notice"]},
}


@pytest.mark.asyncio
async def test_run_agent_raises_on_streamed_error():
client = AdkWebServerClient()
Expand Down
59 changes: 59 additions & 0 deletions tests/unittests/cli/conformance/test_cli_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,65 @@ async def fake_run_agent(req, **kwargs):
)


async def test_run_user_messages_passes_selected_tools_to_replay_client():
"""The spec selection reaches every turn through the conformance client."""
client = MagicMock()
received = []

async def fake_run_agent(request, **kwargs):
received.append(kwargs)
yield Event(author="agent_a")

client.run_agent = fake_run_agent
runner = ConformanceTestRunner([], client)
test_case = TestCase(
category="cat",
name="tc",
dir=None,
test_spec=TestSpec(
description="replay notifications",
agent="app",
replay_tool_responses={"agent_a": ["send_notice"]},
user_messages=[UserMessage(text="first"), UserMessage(text="second")],
),
)

await runner._run_user_messages("session", test_case)

assert [call["replay_tool_responses"] for call in received] == [
{"agent_a": ["send_notice"]},
{"agent_a": ["send_notice"]},
]


async def test_run_all_tests_reports_selected_tools(capsys):
"""The test output makes skipped tool execution visible to the operator."""
runner = ConformanceTestRunner([], MagicMock())
test_case = TestCase(
category="cat",
name="tc",
dir=None,
test_spec=TestSpec(
description="replay notifications",
agent="app",
replay_tool_responses={"agent_a": ["send_notice"]},
),
)
runner._discover_test_cases = lambda: [test_case]

async def replay_case(_):
return _TestResult(category="cat", name="tc", success=True)

runner._run_test_case_replay = replay_case

await runner.run_all_tests()

assert (
"Running cat/tc (recorded tool responses: agent_a.send_notice)..."
in capsys.readouterr().out
)


@pytest.mark.asyncio
async def test_run_user_messages_sse_partial_event_without_id_does_not_mask_final_id():
client = MagicMock()
Expand Down
21 changes: 21 additions & 0 deletions tests/unittests/cli/conformance/test_generated_file_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,32 @@ def test_load_test_case_parses_spec_and_applies_declared_defaults(tmp_path):
assert spec.agent == 'dice_agent'
# Omitted field falls back to its documented empty default.
assert spec.initial_state == {}
assert spec.replay_tool_responses == {}
assert [m.text for m in spec.user_messages] == ['roll a die', 'roll again']
assert spec.user_messages[0].state_delta is None
assert spec.user_messages[1].state_delta == {'rolls': 1}


def test_load_test_case_reads_recorded_tool_selection(tmp_path):
"""A per-agent tool selection can be declared in spec.yaml."""
_write_spec(
tmp_path,
"""\
description: replay notifications
agent: app
replay_tool_responses:
agent_a:
- send_notice
user_messages:
- text: notify
""",
)

spec = load_test_case(tmp_path)

assert spec.replay_tool_responses == {'agent_a': ['send_notice']}


def test_load_test_case_rejects_unknown_spec_field(tmp_path):
"""TestSpec forbids extras so a typo in a hand-written spec is not silent."""
_write_spec(
Expand Down
Loading
Loading