Skip to content

Commit f33d492

Browse files
DeanChensjcopybara-github
authored andcommitted
refactor: unify output_schema routing and avoid duplicate validation
Previously, `basic.py` and `_schema.py` maintained mirrored boolean checks to decide whether `output_schema` could be passed natively in `LlmRequest.config` or required the `set_model_response` tool workaround. Additionally, structured model outputs were validated and deserialized up to three times across `check_and_handle_output_schema`, `LlmAgent.__maybe_save_output_to_state`, and `Workflow` node execution (`process_llm_agent_output`). - Extract `can_set_native_output_schema` in `flows/llm_flows/prompt/_schema.py` as the single source of truth for both `basic.py` and `_OutputSchemaRequestProcessor`. - Preserve the already-validated payload via `_validated_output` on the `Event` across `create_final_model_response_event`, `LlmAgent.__maybe_save_output_to_state`, and `process_llm_agent_output` so `output_schema` validation is not duplicated on the same response event. Co-authored-by: Shangjie Chen <[email protected]> PiperOrigin-RevId: 983562218
1 parent 7babeb0 commit f33d492

7 files changed

Lines changed: 91 additions & 27 deletions

File tree

‎src/google/adk/agents/llm_agent.py‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@
5656
from ..utils._callback_pipeline import _normalize_callbacks
5757
from ..utils._schema_utils import SchemaType
5858
from ..utils._schema_utils import validate_schema
59+
from ..utils.content_utils import extract_text_from_content
5960
from ..utils.context_utils import Aclosing
6061
from ..utils.instructions_utils import InstructionProvider as InstructionProvider
6162
from ..workflow._base_node import BaseNode
@@ -1107,18 +1108,20 @@ def __maybe_save_output_to_state(self, event: Event) -> None:
11071108
if not has_text_part:
11081109
return
11091110

1110-
result = ''.join(
1111-
part.text
1112-
for part in event.content.parts
1113-
if part.text and not part.thought
1114-
)
1111+
result: Any = extract_text_from_content(event.content)
11151112
if self.output_schema:
11161113
# If the result from the final chunk is just whitespace or empty,
11171114
# it means this is an empty final chunk of a stream.
11181115
# Do not attempt to parse it as JSON.
11191116
if not result.strip():
11201117
return
1121-
result = validate_schema(self.output_schema, result)
1118+
if (
1119+
validated_output := getattr(event, '_validated_output', None)
1120+
) is not None:
1121+
result = validated_output
1122+
else:
1123+
result = validate_schema(self.output_schema, result)
1124+
object.__setattr__(event, '_validated_output', result)
11221125
event.actions.state_delta[self.output_key] = result
11231126

11241127
def __maybe_accumulate_streaming_output(

‎src/google/adk/flows/llm_flows/_live_llm_flow.py‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -622,10 +622,10 @@ async def postprocess_live_flow(
622622
)
623623
):
624624
# Create and yield a final model response event
625-
final_event = (
626-
_output_schema_processor.create_final_model_response_event(
627-
invocation_context, json_response
628-
)
625+
final_event = _output_schema_processor.create_final_model_response_event(
626+
invocation_context,
627+
json_response,
628+
validated_response=function_response_event.actions.set_model_response,
629629
)
630630
yield final_event
631631

‎src/google/adk/flows/llm_flows/base_llm_flow.py‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -712,10 +712,10 @@ async def _postprocess_handle_function_calls_async(
712712
function_response_event
713713
):
714714
# Create and yield a final model response event
715-
final_event = (
716-
_output_schema_processor.create_final_model_response_event(
717-
invocation_context, json_response
718-
)
715+
final_event = _output_schema_processor.create_final_model_response_event(
716+
invocation_context,
717+
json_response,
718+
validated_response=function_response_event.actions.set_model_response,
719719
)
720720
yield final_event
721721

‎src/google/adk/flows/llm_flows/basic.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
from .core._utils import copy_http_options as _copy_http_options
3131
from .core._utils import copy_or_none as _copy_or_none
3232
from .core._utils import require_run_config
33+
from .prompt import _schema as _output_schema_processor
3334

3435

3536
def _merge_run_config_http_options(
@@ -133,9 +134,8 @@ def _build_basic_request(
133134
# task-mode agents skip output_schema configuration in
134135
# the basic flow. Structured output for tasks is collected via the
135136
# finish_task tool schema instead.
136-
if getattr(agent, 'mode', None) != 'task' and agent.output_schema:
137-
if not agent.tools or model.capabilities.output_schema_and_tools:
138-
llm_request.set_output_schema(agent.output_schema)
137+
if _output_schema_processor.can_set_native_output_schema(agent):
138+
llm_request.set_output_schema(agent.output_schema)
139139

140140
# A live session reads `live_connect_config`, not `llm_request.config`, so
141141
# the agent's sampling settings would not otherwise reach it.

‎src/google/adk/flows/llm_flows/prompt/_schema.py‎

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,9 @@
1717
from __future__ import annotations
1818

1919
import json
20+
from typing import Any
2021
from typing import AsyncGenerator
22+
from typing import TYPE_CHECKING
2123

2224
from typing_extensions import override
2325

@@ -29,6 +31,18 @@
2931
from ..core._utils import as_llm_agent
3032
from ..core._utils import require_agent_name
3133

34+
if TYPE_CHECKING:
35+
from ....agents.llm_agent import LlmAgent
36+
37+
38+
def can_set_native_output_schema(agent: LlmAgent) -> bool:
39+
"""Returns whether output_schema can be set natively on LlmRequest."""
40+
if not agent.output_schema or agent.mode == 'task':
41+
return False
42+
if not agent.tools:
43+
return True
44+
return bool(agent.canonical_model.capabilities.output_schema_and_tools)
45+
3246

3347
class _OutputSchemaRequestProcessor(BaseLlmRequestProcessor):
3448
"""Processor that handles output schema for agents with tools."""
@@ -44,9 +58,8 @@ async def run_async(
4458
# schema with tools
4559
if (
4660
not agent.output_schema
47-
or not agent.tools
48-
or agent.canonical_model.capabilities.output_schema_and_tools
49-
or getattr(agent, 'mode', None) == 'task'
61+
or agent.mode == 'task'
62+
or can_set_native_output_schema(agent)
5063
):
5164
return
5265

@@ -69,13 +82,17 @@ async def run_async(
6982

7083

7184
def create_final_model_response_event(
72-
invocation_context: InvocationContext, json_response: str
85+
invocation_context: InvocationContext,
86+
json_response: str,
87+
*,
88+
validated_response: Any = None,
7389
) -> Event:
7490
"""Create a final model response event from set_model_response JSON.
7591
7692
Args:
7793
invocation_context: The invocation context.
7894
json_response: The JSON response from set_model_response tool.
95+
validated_response: Optional pre-validated structured response payload.
7996
8097
Returns:
8198
A new Event that looks like a normal model response.
@@ -91,6 +108,8 @@ def create_final_model_response_event(
91108
final_event.content = types.Content(
92109
role='model', parts=[types.Part(text=json_response)]
93110
)
111+
if validated_response is not None:
112+
object.__setattr__(final_event, '_validated_output', validated_response)
94113
return final_event
95114

96115

‎src/google/adk/workflow/_llm_agent_wrapper.py‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
from ..events.event import Event
3232
from ..flows.llm_flows.functions import REQUEST_CONFIRMATION_FUNCTION_CALL_NAME
3333
from ..utils._schema_utils import validate_schema
34+
from ..utils.content_utils import extract_text_from_content
3435
from ..utils.content_utils import to_user_content
3536
from ._errors import WorkflowConfigurationError
3637
from ._errors import WorkflowInvariantError
@@ -370,14 +371,15 @@ def process_llm_agent_output(
370371
return
371372

372373
output = None
373-
text = (
374-
''.join(p.text for p in event.content.parts if p.text and not p.thought)
375-
if event.content.parts
376-
else ''
377-
)
374+
text = extract_text_from_content(event.content)
378375
if agent.output_schema:
379376
if text.strip():
380-
output = validate_schema(agent.output_schema, text)
377+
if (
378+
validated_output := getattr(event, '_validated_output', None)
379+
) is not None:
380+
output = validated_output
381+
else:
382+
output = validate_schema(agent.output_schema, text)
381383
else:
382384
output = None
383385
else:

‎tests/unittests/flows/llm_flows/prompt/test_schema.py‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -595,3 +595,43 @@ async def test_flow_yields_only_function_response_for_normal_tools():
595595
assert first_event.get_function_responses()[0].response == {
596596
'result': 'Searched for: test query'
597597
}
598+
599+
600+
@pytest.mark.asyncio
601+
async def test_output_schema_validated_once_across_agent_and_workflow_node(
602+
mocker,
603+
):
604+
"""Verifies output_schema is not re-validated when set_model_response or output_key already validated it."""
605+
from google.adk.agents.context import Context
606+
from google.adk.flows.llm_flows.prompt._schema import create_final_model_response_event
607+
from google.adk.workflow._llm_agent_wrapper import process_llm_agent_output
608+
609+
agent = LlmAgent(
610+
name='test_agent',
611+
model='gemini-2.5-flash',
612+
output_schema=PersonSchema,
613+
output_key='person',
614+
)
615+
invocation_context = await _create_invocation_context(agent)
616+
ctx = Context(invocation_context)
617+
618+
validate_spy = mocker.spy(
619+
PersonSchema,
620+
'model_validate_json',
621+
)
622+
623+
final_event = create_final_model_response_event(
624+
invocation_context,
625+
'{"name": "Alice", "age": 30, "city": "NYC"}',
626+
validated_response={'name': 'Alice', 'age': 30, 'city': 'NYC'},
627+
)
628+
agent._LlmAgent__maybe_save_output_to_state(final_event)
629+
process_llm_agent_output(agent, ctx, final_event)
630+
631+
assert final_event.actions.state_delta['person'] == {
632+
'name': 'Alice',
633+
'age': 30,
634+
'city': 'NYC',
635+
}
636+
assert final_event.output == {'name': 'Alice', 'age': 30, 'city': 'NYC'}
637+
assert validate_spy.call_count == 0

0 commit comments

Comments
 (0)