Skip to content
Closed
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
38 changes: 34 additions & 4 deletions src/google/adk/agents/llm/task/_finish_task_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

from __future__ import annotations

import copy
from typing import Any
from typing import Optional
from typing import TYPE_CHECKING
Expand All @@ -27,6 +28,7 @@

from ....events.event import Event
from ....tools.base_tool import BaseTool
from ....utils._schema_utils import lowercase_schema_types
from ....utils._schema_utils import schema_to_json_schema
from ....utils._schema_utils import SchemaType
from ._task_models import _DefaultTaskOutput
Expand Down Expand Up @@ -67,6 +69,20 @@ def get_output_wrapper_key(
)


def _raw_schema_to_json_schema(
schema: dict[str, Any] | types.Schema,
) -> dict[str, Any]:
"""Converts a raw dict or ``types.Schema`` output schema to JSON Schema."""
if isinstance(schema, types.Schema):
raw_schema = schema.model_dump(
by_alias=True, exclude_none=True, mode='json'
)
else:
raw_schema = copy.deepcopy(schema)
lowercase_schema_types(raw_schema)
return raw_schema


class FinishTaskTool(BaseTool):
"""Tool for signaling LlmAgent task completion.

Expand All @@ -92,12 +108,22 @@ def __init__(
self.output_schema: SchemaType = (
output_schema if output_schema is not None else _DefaultTaskOutput
)
self._adapter: TypeAdapter[Any] = TypeAdapter(self.output_schema)
raw_schema = self._adapter.json_schema()
# A raw dict or ``types.Schema`` is already a schema, not a Python type.
# ``TypeAdapter`` would read a dict as a pydantic core schema and fail,
# so these are converted directly and, like ``validate_node_data``,
# their values are not validated.
self._adapter: TypeAdapter[Any] | None
self._raw_schema: dict[str, Any]
if isinstance(self.output_schema, (dict, types.Schema)):
self._adapter = None
self._raw_schema = _raw_schema_to_json_schema(self.output_schema)
else:
self._adapter = TypeAdapter(self.output_schema)
self._raw_schema = self._adapter.json_schema()
# FunctionDeclaration parameters must be a JSON object schema.
# If the schema is already an object (e.g. BaseModel), use it directly.
# Otherwise wrap it in an object with a single key.
self._wrapper_key: str | None = get_output_wrapper_key(raw_schema)
self._wrapper_key: str | None = get_output_wrapper_key(self._raw_schema)

description = (
'Signal that this agent has completed its delegated task. Call this'
Expand All @@ -114,7 +140,8 @@ def __init__(
@override
def _get_declaration(self) -> Optional[types.FunctionDeclaration]:
"""Get the function declaration for this tool."""
raw_schema = self._adapter.json_schema()
# Copy so popping $defs below does not change the stored schema.
raw_schema = copy.deepcopy(self._raw_schema)
if self._wrapper_key:
# Extract $defs to the root level so $ref pointers remain valid
# after wrapping the schema inside an object property.
Expand Down Expand Up @@ -184,6 +211,9 @@ async def run_async(
Returns:
Confirmation message, or error dict if validation fails.
"""
if self._adapter is None:
return FINISH_TASK_SUCCESS_RESULT

try:
raw_value = args.get(self._wrapper_key) if self._wrapper_key else args
validated = self._adapter.validate_python(raw_value)
Expand Down
89 changes: 89 additions & 0 deletions tests/unittests/agents/llm/task/test_finish_task_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

from google.adk.agents.llm.task._finish_task_tool import FINISH_TASK_TOOL_NAME
from google.adk.agents.llm.task._finish_task_tool import FinishTaskTool
from google.genai import types
from pydantic import BaseModel
import pytest

Expand Down Expand Up @@ -361,3 +362,91 @@ def test_get_declaration_list_basemodel_defs_at_root(self):
assert 'SampleOutputSchema' in schema['$defs']
# The nested result schema should not contain $defs
assert '$defs' not in schema['properties']['result']

def test_dict_output_schema_object(self):
"""A raw dict object schema is used as the declaration directly."""
schema = {
'type': 'object',
'properties': {'answer': {'type': 'string'}},
'required': ['answer'],
}
tool = FinishTaskTool(task_agent=_make_task_agent(output_schema=schema))

declaration = tool._get_declaration()

assert tool._wrapper_key is None
assert declaration.parameters_json_schema == schema

def test_dict_output_schema_non_object_is_wrapped(self):
"""A raw dict non-object schema is wrapped under the result key."""
schema = {'type': 'array', 'items': {'type': 'string'}}
tool = FinishTaskTool(task_agent=_make_task_agent(output_schema=schema))

declaration = tool._get_declaration()

assert tool._wrapper_key == 'result'
assert declaration.parameters_json_schema == {
'type': 'object',
'properties': {'result': schema},
'required': ['result'],
}

def test_empty_dict_output_schema(self):
"""An empty dict schema builds and is wrapped under the result key."""
tool = FinishTaskTool(task_agent=_make_task_agent(output_schema={}))

declaration = tool._get_declaration()

assert tool._wrapper_key == 'result'
assert declaration.parameters_json_schema['properties'] == {'result': {}}

def test_dict_output_schema_is_not_mutated(self):
"""Building the declaration leaves the caller's schema unchanged."""
schema = {
'type': 'ARRAY',
'items': {'$ref': '#/$defs/Item'},
'$defs': {'Item': {'type': 'STRING'}},
}
original = {
'type': 'ARRAY',
'items': {'$ref': '#/$defs/Item'},
'$defs': {'Item': {'type': 'STRING'}},
}
tool = FinishTaskTool(task_agent=_make_task_agent(output_schema=schema))

first = tool._get_declaration().parameters_json_schema
second = tool._get_declaration().parameters_json_schema

assert schema == original
assert first == second
assert first['$defs'] == {'Item': {'type': 'string'}}

def test_genai_schema_output_schema(self):
"""A types.Schema is converted to a lowercase JSON Schema."""
schema = types.Schema(
type=types.Type.OBJECT,
properties={'answer': types.Schema(type=types.Type.STRING)},
required=['answer'],
)
tool = FinishTaskTool(task_agent=_make_task_agent(output_schema=schema))

declaration = tool._get_declaration()

assert tool._wrapper_key is None
assert declaration.parameters_json_schema == {
'type': 'object',
'properties': {'answer': {'type': 'string'}},
'required': ['answer'],
}

@pytest.mark.asyncio
async def test_run_async_with_dict_output_schema(self):
"""A raw dict schema's finish_task call completes without validation."""
schema = {'type': 'object', 'properties': {'answer': {'type': 'string'}}}
tool = FinishTaskTool(task_agent=_make_task_agent(output_schema=schema))

result = await tool.run_async(
args={'answer': 'done'}, tool_context=mock.MagicMock()
)

assert result == 'Task completed.'
Loading