Skip to content

Commit c742022

Browse files
GWealecopybara-github
authored andcommitted
chore: fix mypy strict type errors in adk agents
Co-authored-by: George Weale <gweale@google.com> PiperOrigin-RevId: 945259368
1 parent ed579c1 commit c742022

11 files changed

Lines changed: 52 additions & 40 deletions

src/google/adk/agents/active_streaming_tool.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
from __future__ import annotations
1616

1717
import asyncio
18+
from typing import Any
1819
from typing import Optional
1920

2021
from pydantic import BaseModel
@@ -32,7 +33,7 @@ class ActiveStreamingTool(BaseModel):
3233
)
3334
"""The pydantic model config."""
3435

35-
task: Optional[asyncio.Task] = None
36+
task: Optional[asyncio.Task[Any]] = None
3637
"""The active task of this streaming tool."""
3738

3839
stream: Optional[LiveRequestQueue] = None

src/google/adk/agents/base_agent.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -581,7 +581,7 @@ def model_post_init(self, __context: Any) -> None:
581581

582582
@field_validator('name', mode='after')
583583
@classmethod
584-
def validate_name(cls, value: str):
584+
def validate_name(cls, value: str) -> str:
585585
if not value.isidentifier():
586586
raise ValueError(
587587
f'Found invalid agent name: `{value}`.'

src/google/adk/agents/config_agent_utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -264,7 +264,7 @@ def resolve_agent_reference(
264264
raise ValueError("AgentRefConfig must have either 'code' or 'config_path'")
265265

266266

267-
def _resolve_agent_code_reference(code: str) -> Any:
267+
def _resolve_agent_code_reference(code: str) -> BaseAgent:
268268
"""Resolve a code reference to an actual agent instance.
269269
270270
Args:

src/google/adk/agents/context.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -86,8 +86,8 @@ def _derive_node_path(
8686

8787
if not parent_path and isinstance(node, BaseAgent) and node.parent_agent:
8888
path_builder = _NodePathBuilder([])
89-
curr = node.parent_agent
90-
parent_agents = []
89+
curr: BaseAgent | None = node.parent_agent
90+
parent_agents: list[BaseAgent] = []
9191
depth = 0
9292
while curr is not None and depth < _MAX_PARENT_DEPTH:
9393
parent_agents.insert(0, curr)

src/google/adk/agents/invocation_context.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@
1616

1717
import asyncio
1818
from typing import Any
19-
from typing import cast
2019
from typing import Optional
2120

2221
from google.adk.platform import uuid as platform_uuid
@@ -84,7 +83,7 @@ class _InvocationCostManager(BaseModel):
8483

8584
def increment_and_enforce_llm_calls_limit(
8685
self, run_config: Optional[RunConfig]
87-
):
86+
) -> None:
8887
"""Increments _number_of_llm_calls and enforces the limit."""
8988
# We first increment the counter and then check the conditions.
9089
self._number_of_llm_calls += 1
@@ -389,7 +388,7 @@ def populate_invocation_agent_states(self) -> None:
389388

390389
def increment_llm_call_count(
391390
self,
392-
):
391+
) -> None:
393392
"""Tracks number of llm calls made.
394393
395394
Raises:
@@ -525,4 +524,4 @@ def stamp_event_branch_context(self, event: Event) -> None:
525524

526525

527526
def new_invocation_context_id() -> str:
528-
return "e-" + cast(str, platform_uuid.new_uuid())
527+
return "e-" + platform_uuid.new_uuid()

src/google/adk/agents/langgraph_agent.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919

2020
from google.genai import types
2121
from langchain_core.messages import AIMessage
22+
from langchain_core.messages import BaseMessage
2223
from langchain_core.messages import HumanMessage
2324
from langchain_core.messages import SystemMessage
2425
from langchain_core.runnables.config import RunnableConfig
@@ -31,7 +32,9 @@
3132
from .invocation_context import InvocationContext
3233

3334

34-
def _get_last_human_messages(events: list[Event]) -> list[HumanMessage]:
35+
def _get_last_human_messages(
36+
events: list[Event],
37+
) -> list[Union[HumanMessage, AIMessage]]:
3538
"""Extracts last human messages from given list of events.
3639
3740
Args:
@@ -40,7 +43,7 @@ def _get_last_human_messages(events: list[Event]) -> list[HumanMessage]:
4043
Returns:
4144
list of last human messages
4245
"""
43-
messages = []
46+
messages: list[Union[HumanMessage, AIMessage]] = []
4447
for event in reversed(events):
4548
if messages and event.author != 'user':
4649
break
@@ -77,7 +80,7 @@ async def _run_async_impl(
7780
if current_graph_state.values
7881
else []
7982
)
80-
messages = (
83+
messages: list[BaseMessage] = (
8184
[SystemMessage(content=self.instruction)]
8285
if self.instruction and not graph_messages
8386
else []
@@ -132,7 +135,7 @@ def _get_conversation_with_agent(
132135
list of messages
133136
"""
134137

135-
messages = []
138+
messages: list[Union[HumanMessage, AIMessage]] = []
136139
for event in events:
137140
if not event.content or not event.content.parts:
138141
continue

src/google/adk/agents/live_request_queue.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -62,27 +62,27 @@ class LiveRequest(BaseModel):
6262
class LiveRequestQueue:
6363
"""Queue used to send LiveRequest in a live(bidirectional streaming) way."""
6464

65-
def __init__(self):
66-
self._queue = asyncio.Queue()
65+
def __init__(self) -> None:
66+
self._queue: asyncio.Queue[LiveRequest] = asyncio.Queue()
6767

68-
def close(self):
68+
def close(self) -> None:
6969
self._queue.put_nowait(LiveRequest(close=True))
7070

71-
def send_content(self, content: types.Content, partial: bool = False):
71+
def send_content(self, content: types.Content, partial: bool = False) -> None:
7272
self._queue.put_nowait(LiveRequest(content=content, partial=partial))
7373

74-
def send_realtime(self, blob: types.Blob):
74+
def send_realtime(self, blob: types.Blob) -> None:
7575
self._queue.put_nowait(LiveRequest(blob=blob))
7676

77-
def send_activity_start(self):
77+
def send_activity_start(self) -> None:
7878
"""Sends an activity start signal to mark the beginning of user input."""
7979
self._queue.put_nowait(LiveRequest(activity_start=types.ActivityStart()))
8080

81-
def send_activity_end(self):
81+
def send_activity_end(self) -> None:
8282
"""Sends an activity end signal to mark the end of user input."""
8383
self._queue.put_nowait(LiveRequest(activity_end=types.ActivityEnd()))
8484

85-
def send(self, req: LiveRequest):
85+
def send(self, req: LiveRequest) -> None:
8686
self._queue.put_nowait(req)
8787

8888
async def get(self) -> LiveRequest:

src/google/adk/agents/llm_agent.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@
2323
from typing import AsyncGenerator
2424
from typing import Awaitable
2525
from typing import Callable
26-
from typing import cast
2726
from typing import ClassVar
2827
from typing import Dict
2928
from typing import Literal
@@ -64,6 +63,7 @@
6463
from .base_agent import BaseAgentState
6564
from .base_agent_config import BaseAgentConfig as BaseAgentConfig
6665
from .callback_context import CallbackContext
66+
from .context import Context
6767
from .invocation_context import InvocationContext
6868
from .llm_agent_config import LlmAgentConfig as LlmAgentConfig
6969
from .readonly_context import ReadonlyContext
@@ -138,7 +138,7 @@
138138

139139
async def _convert_tool_union_to_tools(
140140
tool_union: ToolUnion,
141-
ctx: ReadonlyContext,
141+
ctx: Optional[ReadonlyContext],
142142
model: Union[str, BaseLlm],
143143
multiple_tools: bool = False,
144144
) -> list[BaseTool]:
@@ -152,7 +152,7 @@ async def _convert_tool_union_to_tools(
152152
from ..tools.google_search_agent_tool import create_google_search_agent
153153
from ..tools.google_search_agent_tool import GoogleSearchAgentTool
154154

155-
search_tool = cast(GoogleSearchTool, tool_union)
155+
search_tool = tool_union
156156
if search_tool.bypass_multi_tools_limit:
157157
return [GoogleSearchAgentTool(create_google_search_agent(model))]
158158

@@ -163,7 +163,7 @@ async def _convert_tool_union_to_tools(
163163
if multiple_tools and isinstance(tool_union, VertexAiSearchTool):
164164
from ..tools.discovery_engine_search_tool import DiscoveryEngineSearchTool
165165

166-
vais_tool = cast(VertexAiSearchTool, tool_union)
166+
vais_tool = tool_union
167167
if vais_tool.bypass_multi_tools_limit:
168168
return [
169169
DiscoveryEngineSearchTool(
@@ -927,7 +927,7 @@ def _get_available_agent_names(self) -> list[str]:
927927
"""
928928
agents = []
929929

930-
def collect_agents(agent):
930+
def collect_agents(agent: BaseAgent) -> None:
931931
agents.append(agent.name)
932932
if hasattr(agent, 'sub_agents') and agent.sub_agents:
933933
for sub_agent in agent.sub_agents:
@@ -952,7 +952,7 @@ def __get_transfer_to_agent_or_none(
952952
return self.__get_agent_to_run(event.actions.transfer_to_agent)
953953
return None
954954

955-
def __maybe_save_output_to_state(self, event: Event):
955+
def __maybe_save_output_to_state(self, event: Event) -> None:
956956
"""Saves the model output to state if needed."""
957957
# skip if the event was authored by some other agent (e.g. current agent
958958
# transferred to another agent)

src/google/adk/agents/parallel_agent.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,9 @@ async def _merge_agent_run(
6060

6161
# Agents are processed in parallel.
6262
# Events for each agent are put on queue sequentially.
63-
async def process_an_agent(events_for_one_agent):
63+
async def process_an_agent(
64+
events_for_one_agent: AsyncGenerator[Event, None],
65+
) -> None:
6466
try:
6567
async for event in events_for_one_agent:
6668
resume_signal = asyncio.Event()
@@ -112,7 +114,7 @@ async def _merge_agent_run_pre_3_11(
112114
sentinel = object()
113115
queue = asyncio.Queue()
114116

115-
def propagate_exceptions(tasks):
117+
def propagate_exceptions(tasks: list[asyncio.Task[None]]) -> None:
116118
# Propagate exceptions and errors from tasks.
117119
for task in tasks:
118120
if task.done():
@@ -122,7 +124,9 @@ def propagate_exceptions(tasks):
122124

123125
# Agents are processed in parallel.
124126
# Events for each agent are put on queue sequentially.
125-
async def process_an_agent(events_for_one_agent):
127+
async def process_an_agent(
128+
events_for_one_agent: AsyncGenerator[Event, None],
129+
) -> None:
126130
try:
127131
async for event in events_for_one_agent:
128132
resume_signal = asyncio.Event()

src/google/adk/agents/remote_a2a_agent.py

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -408,7 +408,7 @@ def _create_a2a_request_for_user_function_response(
408408
return a2a_message
409409

410410
def _is_remote_response(self, event: Event) -> bool:
411-
return (
411+
return bool(
412412
event.author == self.name
413413
and event.custom_metadata
414414
and event.custom_metadata.get(A2A_METADATA_PREFIX + "response", False)
@@ -448,22 +448,27 @@ def _construct_message_parts_from_session(
448448
events_to_process.append(event)
449449

450450
for event in reversed(events_to_process):
451+
processed_event: Optional[Event] = event
451452
if _is_other_agent_reply(self.name, event):
452-
event = _present_other_agent_message(event)
453+
processed_event = _present_other_agent_message(event)
453454

454-
if not event or not event.content or not event.content.parts:
455+
if (
456+
not processed_event
457+
or not processed_event.content
458+
or not processed_event.content.parts
459+
):
455460
continue
456461

457-
for part in event.content.parts:
462+
for part in processed_event.content.parts:
458463
converted_parts = self._genai_part_converter(part)
459464
if not isinstance(converted_parts, list):
460465
converted_parts = [converted_parts] if converted_parts else []
461466

462-
if event.author == "user":
463-
for part in converted_parts:
464-
meta = _compat.part_metadata(part) or {}
467+
if processed_event.author == "user":
468+
for a2a_part in converted_parts:
469+
meta = _compat.part_metadata(a2a_part) or {}
465470
meta["is_user_input"] = True
466-
_compat.set_part_metadata(part, meta)
471+
_compat.set_part_metadata(a2a_part, meta)
467472

468473
if converted_parts:
469474
message_parts.extend(converted_parts)

0 commit comments

Comments
 (0)