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
64 changes: 35 additions & 29 deletions src/google/adk/runners.py
Original file line number Diff line number Diff line change
Expand Up @@ -1190,27 +1190,36 @@ async def run_async(
# finish_task tool and its result is promoted onto the terminal event's
# output field (an A2A server turns that into an artifact; a direct caller
# reads it off the event stream).
if effective_mode in (_AgentMode.CHAT, _AgentMode.TASK):
session = await self._get_or_create_session(
user_id=user_id,
session_id=session_id,
get_session_config=run_config.get_session_config,
)
agent_to_run: BaseAgent
if self._uses_legacy_sub_agent_picker():
agent_to_run = self._find_agent_to_run(
_session_for_routing(session, new_message), self.agent
)
else:
agent_to_run = self.agent

# The agent_to_run will be built/cloned inside Context.run_node,
# so we don't call build_node here to avoid double cloning.
else:
if effective_mode not in (_AgentMode.CHAT, _AgentMode.TASK):
raise ValueError(
"LlmAgent as root agent must have mode='chat' or 'task', but got"
f" mode='{effective_mode}'."
)

session = await self._get_or_create_session(
user_id=user_id,
session_id=session_id,
get_session_config=run_config.get_session_config,
)

if not invocation_id and new_message is None and not session.events:
raise ValueError(
'Running an agent requires either a new_message or an '
'invocation_id to resume a previous invocation. '
f'Session: {session_id}, User: {user_id}'
)

if isinstance(self.agent, LlmAgent):
agent_to_run: BaseAgent
if self._uses_legacy_sub_agent_picker():
agent_to_run = self._find_agent_to_run(
_session_for_routing(session, new_message), self.agent
)
else:
agent_to_run = self.agent

# The agent_to_run will be built/cloned inside Context.run_node,
# so we don't call build_node here to avoid double cloning.
async with aclosing(
self._run_node_async(
user_id=user_id,
Expand Down Expand Up @@ -1243,6 +1252,8 @@ async def run_async(
state_delta=state_delta,
run_config=run_config,
yield_user_message=yield_user_message,
node=self.agent,
session=session,
abort_signal=abort_signal,
)
) as agen:
Expand All @@ -1255,18 +1266,13 @@ async def run_async(
async def _run_with_trace(
new_message: types.Content | None = None,
invocation_id: str | None = None,
session: Session | None = None,
) -> AsyncGenerator[Event, None]:
session = await self._get_or_create_session(
user_id=user_id,
session_id=session_id,
get_session_config=run_config.get_session_config,
)

if not invocation_id and new_message is None:
raise ValueError(
'Running an agent requires either a new_message or an '
'invocation_id to resume a previous invocation. '
f'Session: {session_id}, User: {user_id}'
if session is None:
session = await self._get_or_create_session(
user_id=user_id,
session_id=session_id,
get_session_config=run_config.get_session_config,
)

is_resumable = (
Expand Down Expand Up @@ -1380,7 +1386,7 @@ async def execute(
async with aclosing(
_instrumentation.stream_in_scope(
invocation_otel_context,
_run_with_trace(new_message, invocation_id),
_run_with_trace(new_message, invocation_id, session=session),
)
) as agen:
async for event in agen:
Expand Down
225 changes: 220 additions & 5 deletions tests/unittests/test_runners.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,6 @@
from google.adk.sessions.base_session_service import GetSessionConfig
from google.adk.sessions.in_memory_session_service import InMemorySessionService
from google.adk.sessions.session import Session
from google.adk.tools.agent_tool import AgentTool
from google.adk.tools.base_toolset import BaseToolset
from google.adk.tools.function_tool import FunctionTool
from google.adk.tools.long_running_tool import LongRunningFunctionTool
Expand Down Expand Up @@ -1396,15 +1395,14 @@ async def test_runner_root_task_mode_writes_output_key_to_session_state():

@pytest.mark.asyncio
async def test_runner_raises_on_root_llm_agent_with_single_turn_mode():
"""Runner raises ValueError if root LlmAgent runs with mode='single_turn'."""
"""Runner raises ValueError if root LlmAgent runs with mode='single_turn' before fetching session."""
session_service = InMemorySessionService()
spy = AsyncMock(wraps=session_service.get_session)
session_service.get_session = spy
agent = LlmAgent(name="single_turn_agent", mode="single_turn")
runner = Runner(
app_name=TEST_APP_ID, agent=agent, session_service=session_service
)
await session_service.create_session(
app_name=TEST_APP_ID, user_id=TEST_USER_ID, session_id=TEST_SESSION_ID
)

with pytest.raises(
ValueError,
Expand All @@ -1422,6 +1420,8 @@ async def test_runner_raises_on_root_llm_agent_with_single_turn_mode():
):
pass

spy.assert_not_called()


@pytest.mark.asyncio
async def test_chat_mode_fetches_session_once_per_turn():
Expand Down Expand Up @@ -7441,5 +7441,220 @@ async def _consume():
assert not [e for e in session.events if e.actions.compaction]


async def test_run_async_llm_agent_without_message_or_invocation_id_raises_value_error():
"""Runner.run_async must raise ValueError when both new_message and invocation_id are None (#7934)."""
session_service = InMemorySessionService()
runner = Runner(
app_name="test_app",
agent=MockLlmAgent("test_agent"),
session_service=session_service,
auto_create_session=True,
)
with pytest.raises(
ValueError,
match=r"Running an agent requires either a new_message or an invocation_id",
):
agen = runner.run_async(
user_id="u",
session_id="s",
new_message=None,
invocation_id=None,
)
async for _ in agen:
pass


async def test_run_async_base_node_without_message_or_invocation_id_raises_value_error():
"""Runner.run_async with BaseNode root must raise ValueError when both new_message and invocation_id are None (#7934)."""
from google.adk.workflow._base_node import BaseNode

session_service = InMemorySessionService()
node = BaseNode(name="test_node")
runner = Runner(
app=App(name="test_app", root_agent=node),
session_service=session_service,
auto_create_session=True,
)
with pytest.raises(
ValueError,
match=r"Running an agent requires either a new_message or an invocation_id",
):
agen = runner.run_async(
user_id="u",
session_id="s",
new_message=None,
invocation_id=None,
)
async for _ in agen:
pass


async def test_run_async_with_existing_history_and_no_new_message_succeeds():
"""Runner.run_async must succeed with new_message=None when session has history (#7934)."""
session_service = InMemorySessionService()
session = await session_service.create_session(
app_name="test_app", user_id="u", session_id="s"
)
user_event = Event(
timestamp=1.0,
invocation_id="inv1",
author="user",
content=types.Content(
role="user", parts=[types.Part(text="hello previous")]
),
)
await session_service.append_event(session=session, event=user_event)

mock_model = testing_utils.MockModel.create(responses=["ok"])
agent = LlmAgent(name="test_agent", model=mock_model)
runner = Runner(
app_name="test_app",
agent=agent,
session_service=session_service,
)

events = [
e
async for e in runner.run_async(
user_id="u",
session_id="s",
new_message=None,
invocation_id=None,
)
]
assert events
assert len(mock_model.requests) == 1
assert any(
any(part.text == "hello previous" for part in c.parts)
for c in mock_model.requests[0].contents
if c.role == "user"
)


async def test_run_async_workflow_root_with_existing_history_and_no_new_message_succeeds():
"""Runner.run_async with Workflow root must succeed with new_message=None when session has history (#7934)."""
from google.adk.workflow import START, Workflow

session_service = InMemorySessionService()
session = await session_service.create_session(
app_name="test_app", user_id="u", session_id="s"
)
user_event = Event(
timestamp=1.0,
invocation_id="inv1",
author="user",
content=types.Content(
role="user", parts=[types.Part(text="hello previous")]
),
)
await session_service.append_event(session=session, event=user_event)

mock_model = testing_utils.MockModel.create(responses=["workflow reply"])
agent = LlmAgent(name="test_agent", model=mock_model)
workflow = Workflow(name="test_wf", edges=[(START, agent)])
runner = Runner(
app_name="test_app",
agent=workflow,
session_service=session_service,
)

events = [
e
async for e in runner.run_async(
user_id="u",
session_id="s",
new_message=None,
invocation_id=None,
)
]
assert events
assert len(mock_model.requests) == 1
assert any(
any(part.text == "hello previous" for part in c.parts)
for c in mock_model.requests[0].contents
if c.role == "user"
)


async def test_run_async_sequential_agent_root_empty_and_history_cases():
"""Runner.run_async with SequentialAgent (BaseAgent) root checks empty session and proceeds with history (#7934)."""
from google.adk.agents.sequential_agent import SequentialAgent

session_service = InMemorySessionService()

# 1. Empty session: without new_message or invocation_id, raises ValueError before execution
empty_session = await session_service.create_session(
app_name="test_app", user_id="u", session_id="s_empty"
)
mock_model1 = testing_utils.MockModel.create(responses=["step1"])
seq1 = SequentialAgent(
name="seq1", sub_agents=[LlmAgent(name="sub1", model=mock_model1)]
)
runner1 = Runner(
app=App(
name="test_app",
root_agent=seq1,
resumability_config=ResumabilityConfig(is_resumable=True),
),
session_service=session_service,
)

with pytest.raises(
ValueError,
match=r"Running an agent requires either a new_message or an invocation_id",
):
async for _ in runner1.run_async(
user_id="u",
session_id=empty_session.id,
new_message=None,
invocation_id=None,
):
pass

# 2. History session: with prior user event and resumable app, proceeds without new_message
history_session = await session_service.create_session(
app_name="test_app", user_id="u", session_id="s_history"
)
user_event = Event(
timestamp=1.0,
invocation_id="inv1",
author="user",
content=types.Content(
role="user", parts=[types.Part(text="hello previous")]
),
)
await session_service.append_event(session=history_session, event=user_event)

mock_model2 = testing_utils.MockModel.create(responses=["step1 reply"])
seq2 = SequentialAgent(
name="seq2", sub_agents=[LlmAgent(name="sub2", model=mock_model2)]
)
runner2 = Runner(
app=App(
name="test_app",
root_agent=seq2,
resumability_config=ResumabilityConfig(is_resumable=True),
),
session_service=session_service,
)

events = [
e
async for e in runner2.run_async(
user_id="u",
session_id=history_session.id,
new_message=None,
invocation_id="inv1",
)
]
assert events
assert len(mock_model2.requests) == 1
assert any(
any(part.text == "hello previous" for part in c.parts)
for c in mock_model2.requests[0].contents
if c.role == "user"
)


if __name__ == "__main__":
pytest.main([__file__])
Loading