diff --git a/mobilerun/agent/oneflows/structured_output_agent.py b/mobilerun/agent/oneflows/structured_output_agent.py index f47778cee..860745c61 100644 --- a/mobilerun/agent/oneflows/structured_output_agent.py +++ b/mobilerun/agent/oneflows/structured_output_agent.py @@ -1,17 +1,18 @@ -""" -StructuredOutputAgent - Extract structured data from final answers. - -Takes a raw text answer and a Pydantic model, uses structured_predict() -to extract structured data from the text. +"""Validate whole-answer JSON before asking the LLM to extract it. +Fall back on errors, non-finite output, or unmatched containers (lists match by position). +Nonempty model objects need a recognized field, validation alias, or retained extra; +if any keys are discarded, at least one recognized input value must be non-null. """ import logging +from math import isfinite from typing import Type from llama_index.core.llms.llm import LLM from llama_index.core.prompts import PromptTemplate from llama_index.core.workflow import Context, StartEvent, StopEvent, Workflow, step -from pydantic import BaseModel +from pydantic import AliasChoices, AliasPath, BaseModel, RootModel, ValidationError +from pydantic_core import PydanticUndefined, from_json from mobilerun.agent.utils.errors import describe_error from mobilerun.agent.utils.inference import astructured_predict_with_retries @@ -19,12 +20,18 @@ logger = logging.getLogger("mobilerun") -class StructuredOutputAgent(Workflow): - """ - Agent that extracts structured output from text answers. +def _has_non_finite_float(value: object) -> bool: + if isinstance(value, float): + return not isfinite(value) + if isinstance(value, dict): + return any(_has_non_finite_float(item) for item in value.values()) + if isinstance(value, list): + return any(_has_non_finite_float(item) for item in value) + return False - Uses LLM.structured_predict() to parse text into Pydantic models. - """ + +class StructuredOutputAgent(Workflow): + """Extract structured output from a final answer.""" def __init__( self, @@ -38,26 +45,102 @@ def __init__( self.pydantic_model = pydantic_model self.answer_text = answer_text + @classmethod + def _recognizes_input_objects(cls, answer: object, validated: object) -> bool: + if isinstance(validated, RootModel): + return cls._recognizes_input_objects(answer, validated.root) + if isinstance(answer, list): + if not isinstance(validated, (list, tuple)): + return not answer + return len(answer) == len(validated) and all( + cls._recognizes_input_objects(item, value) + for item, value in zip(answer, validated, strict=True) + ) + if not isinstance(answer, dict): + return True + if isinstance(validated, dict): + return answer.keys() == validated.keys() and all( + cls._recognizes_input_objects(item, validated[key]) + for key, item in answer.items() + ) + if not answer: + return True + if not isinstance(validated, BaseModel): + return False + + # Inspect the original input: validators can add to model_fields_set. + model = type(validated) + by_alias = model.model_config.get("validate_by_alias", True) + by_name = model.model_config.get("validate_by_name", False) + extras = validated.model_extra or {} + extra_keys = answer.keys() & extras.keys() + recognized_keys = extra_keys.copy() + recognized_non_null = any(answer[key] is not None for key in extra_keys) + for name, field in model.model_fields.items(): + alias = field.validation_alias + aliases = alias.choices if isinstance(alias, AliasChoices) else (alias,) + choices = tuple(aliases) if by_alias and alias is not None else () + if by_name or alias is None: + choices += (name,) + for choice in choices: + if isinstance(choice, AliasPath): + key, item = choice.path[0], choice.search_dict_for_path(answer) + else: + key, item = choice, answer.get(choice, PydanticUndefined) + if item is PydanticUndefined: + continue + recognized_keys.add(key) + recognized_non_null |= item is not None + if not cls._recognizes_input_objects(item, getattr(validated, name)): + return False + break + return (recognized_non_null or recognized_keys == answer.keys()) and all( + cls._recognizes_input_objects(answer[key], extras[key]) + for key in extra_keys + ) + @step async def extract_structured_output( self, ctx: Context, ev: StartEvent ) -> StopEvent: - """ - Extract structured output using structured_predict(). - """ logger.debug("🔍 Extracting structured output from final answer...") try: - # Create prompt for extraction - prompt = PromptTemplate( - "Extract structured information from the following text:\n\n{text}" - ) - - # Use structured_predict to extract data - logger.info("🔍 StructuredOutput response:", extra={"color": "magenta"}) - structured_output = await astructured_predict_with_retries( - self.llm, self.pydantic_model, prompt, text=self.answer_text - ) + try: + structured_output = self.pydantic_model.model_validate_json( + self.answer_text + ) + if self.answer_text.lstrip(" \t\r\n").startswith( + ("{", "[") + ) and not self._recognizes_input_objects( + from_json(self.answer_text), structured_output + ): + structured_output = None + + if structured_output is not None and _has_non_finite_float( + structured_output.model_dump(mode="json", by_alias=True) + ): + structured_output = None + except ValidationError: + structured_output = None + except Exception as exc: + logger.debug("Direct JSON parsing failed: %s", type(exc).__name__) + structured_output = None + + if structured_output is None: + logger.debug( + "Direct JSON parsing did not produce usable structured output" + ) + prompt = PromptTemplate( + "Extract structured information from the following text:\n\n{text}" + ) + + logger.info("🔍 StructuredOutput response:", extra={"color": "magenta"}) + structured_output = await astructured_predict_with_retries( + self.llm, self.pydantic_model, prompt, text=self.answer_text + ) + else: + logger.debug("Parsed structured output directly from the JSON answer") logger.debug("✅ Successfully extracted structured output") diff --git a/tests/test_structured_output_agent.py b/tests/test_structured_output_agent.py new file mode 100644 index 000000000..cfa94166c --- /dev/null +++ b/tests/test_structured_output_agent.py @@ -0,0 +1,332 @@ +import asyncio +import logging +from collections import deque +from fractions import Fraction +from types import SimpleNamespace +from unittest.mock import AsyncMock, Mock + +import pytest +from pydantic import ( + AliasChoices, + AliasPath, + BaseModel, + ConfigDict, + Field, + RootModel, + field_serializer, + model_validator, +) +from pydantic.dataclasses import dataclass + +from mobilerun.agent.oneflows import structured_output_agent +from mobilerun.agent.oneflows.structured_output_agent import StructuredOutputAgent + + +class StructuredOutput(BaseModel): + model_config = ConfigDict(extra="forbid") + + value: str + + +class NumericOutput(BaseModel): + value: float + + +class RatioOutput(BaseModel): + ratio: Fraction + + +class NestedOutput(BaseModel): + values: dict[str, list[NumericOutput]] + + +class DarkModeOutput(BaseModel): + model_config = ConfigDict(populate_by_name=True) + + success: bool | None = None + dark_mode_enabled: bool | None = Field(default=None, alias="darkModeEnabled") + + +class SettingsOutput(BaseModel): + settings: DarkModeOutput + + +class SettingsListOutput(BaseModel): + items: list[DarkModeOutput] + + +@dataclass +class DataclassSettings: + settings: DarkModeOutput + + +class DroppedListItemOutput(RootModel[list[DarkModeOutput]]): + @model_validator(mode="after") + def drop_trailing_item(self): + self.root = self.root[:1] + return self + + +class DerivedOutput(BaseModel): + success: bool | None = None + summary: str = "unknown" + + @model_validator(mode="after") + def derive_summary(self): + self.summary = "enabled" if self.success else "unknown" + return self + + +class AliasChoicesOutput(BaseModel): + value: str | None = Field( + default=None, + alias="wireValue", + validation_alias=AliasChoices("alternate", AliasPath("items", 0, "value")), + ) + + +class NameOnlyOutput(BaseModel): + model_config = ConfigDict(validate_by_alias=False) + + value: str | None = Field(default=None, alias="wireValue") + + +class ExtrasOutput(BaseModel): + model_config = ConfigDict(extra="allow") + + +class NormalizedOutput(BaseModel): + value: str = "default" + + @model_validator(mode="before") + @classmethod + def normalize(cls, data): + if isinstance(data, str): + return {"value": data} + if not isinstance(data, dict): + return data + if "legacy_value" in data: + return {"value": data["legacy_value"]} + if data.get("value") == "unknown": + return {} + return data + + +@pytest.fixture +def run_agent(): + def run(answer_text, expected=None, *, model=None, error=None): + predict = AsyncMock(return_value=expected, side_effect=error) + + async def run_workflow(): + agent = StructuredOutputAgent( + llm=SimpleNamespace(astructured_predict=predict), + pydantic_model=model if model is not None else type(expected), + answer_text=answer_text, + ) + return await agent.run() + + return asyncio.run(run_workflow()), predict + + return run + + +@pytest.mark.parametrize( + ("answer_text", "expected"), + [ + (' \n{"value":"direct"}\t ', StructuredOutput(value="direct")), + ('{"value":1.5}', NumericOutput(value=1.5)), + ( + '{"darkModeEnabled":true,"ignored":NaN}', + DarkModeOutput(dark_mode_enabled=True), + ), + ('{"dark_mode_enabled":true}', DarkModeOutput(dark_mode_enabled=True)), + ('{"success":null}', DarkModeOutput()), + ("{}", DerivedOutput()), + ('{"extra":true}', ExtrasOutput(extra=True)), + ("[1, 2]", RootModel[list[int]]([1, 2])), + ("7", RootModel[int](7)), + ('{"alternate":"direct"}', AliasChoicesOutput(alternate="direct")), + ('{"items":[{"value":"path"}]}', AliasChoicesOutput(alternate="path")), + ('{"items":[{"value":null}]}', AliasChoicesOutput()), + ('{"value":"direct"}', NameOnlyOutput(value="direct")), + ('{"value":"unknown"}', NormalizedOutput()), + ( + '{"settings":{"darkModeEnabled":true}}', + SettingsOutput(settings=DarkModeOutput(dark_mode_enabled=True)), + ), + ( + '{"items":[{"darkModeEnabled":true}]}', + SettingsListOutput(items=[DarkModeOutput(dark_mode_enabled=True)]), + ), + ( + '{"darkModeEnabled":true}', + RootModel[DarkModeOutput](DarkModeOutput(dark_mode_enabled=True)), + ), + ( + '{"settings":{"darkModeEnabled":true}}', + RootModel[dict[str, DarkModeOutput]]( + {"settings": DarkModeOutput(dark_mode_enabled=True)} + ), + ), + ], +) +def test_valid_json_skips_llm(run_agent, answer_text, expected): + result, predict = run_agent(answer_text, model=type(expected)) + + assert result == { + "structured_output": expected, + "success": True, + "error_message": "", + } + predict.assert_not_called() + + +def test_scalar_normalized_by_before_validator_skips_second_parse( + run_agent, monkeypatch +): + parse = Mock(wraps=structured_output_agent.from_json) + monkeypatch.setattr(structured_output_agent, "from_json", parse) + + result, predict = run_agent('"direct"', model=NormalizedOutput) + + assert result["success"] is True + assert result["structured_output"] == NormalizedOutput(value="direct") + parse.assert_not_called() + predict.assert_not_called() + + +@pytest.mark.parametrize( + ("answer_text", "inferred"), + [ + ("The value is inferred.", StructuredOutput(value="inferred")), + ('```json\n{"value":"direct"}\n```', StructuredOutput(value="inferred")), + ("{}", StructuredOutput(value="inferred")), + ('{"value": "direct", "extra": true}', StructuredOutput(value="inferred")), + ('{"value":"\ud800"}', StructuredOutput(value="inferred")), + ('{"legacy_value":"direct"}', NormalizedOutput(value="inferred")), + ('{"ratio":{"numerator":1,"denominator":2}}', RatioOutput(ratio="1/2")), + ('{"value":NaN}', NumericOutput(value=1.5)), + ('{"values":{"nested":[{"value":1e999}]}}', NestedOutput(values={})), + ( + '{"message":"Dark mode was successfully enabled"}', + DarkModeOutput(success=True, dark_mode_enabled=True), + ), + ( + '{"success":null,"message":"Dark mode enabled"}', + DarkModeOutput(dark_mode_enabled=True), + ), + ( + '{"settings":{"darkModeEnabled":null,"message":"x"}}', + SettingsOutput(settings=DarkModeOutput(dark_mode_enabled=True)), + ), + ( + '{"items":[{"value":null}],"message":"x"}', + AliasChoicesOutput(alternate="inferred"), + ), + ( + '{"message":"Dark mode was successfully enabled"}', + DerivedOutput(success=True), + ), + ( + '{"items": [{"unrecognized": true}]}', + AliasChoicesOutput(alternate="inferred"), + ), + ('{"wireValue":"ignored"}', AliasChoicesOutput(alternate="inferred")), + ('{"value":"ignored"}', AliasChoicesOutput(alternate="inferred")), + ('{"wireValue":"ignored"}', NameOnlyOutput(value="inferred")), + ( + '{"settings":{"message":"Dark mode enabled"}}', + SettingsOutput(settings=DarkModeOutput(dark_mode_enabled=True)), + ), + ( + '{"items":[{"message":"x"}]}', + SettingsListOutput(items=[DarkModeOutput(dark_mode_enabled=True)]), + ), + ( + '{"message":"x"}', + RootModel[DarkModeOutput](DarkModeOutput(dark_mode_enabled=True)), + ), + ( + '{"settings":{"message":"x"}}', + RootModel[dict[str, DarkModeOutput]]( + {"settings": DarkModeOutput(dark_mode_enabled=True)} + ), + ), + ( + '[{"darkModeEnabled":false},{"message":"x"}]', + DroppedListItemOutput([DarkModeOutput(dark_mode_enabled=True)]), + ), + ( + '{"01":{"darkModeEnabled":false}}', + RootModel[dict[int, DarkModeOutput]]( + {1: DarkModeOutput(dark_mode_enabled=True)} + ), + ), + ( + '[{"message":"x"}]', + RootModel[deque[DarkModeOutput]]( + deque([DarkModeOutput(dark_mode_enabled=True)]) + ), + ), + ( + '{"settings":{"message":"x"}}', + RootModel[DataclassSettings]( + DataclassSettings(DarkModeOutput(dark_mode_enabled=True)) + ), + ), + ], +) +def test_other_answers_use_llm_extraction(run_agent, answer_text, inferred): + result, predict = run_agent(answer_text, inferred) + + assert result == { + "structured_output": inferred, + "success": True, + "error_message": "", + } + predict.assert_awaited_once() + assert predict.await_args.kwargs == {"text": answer_text} + + +def test_json_serialization_error_uses_llm_extraction(run_agent, caplog, monkeypatch): + class SerializableOutput(BaseModel): + value: str + + @field_serializer("value", when_used="json") + def serialize_value(self, value): + if not value: + raise ValueError("private exception text") + return value + + inferred = SerializableOutput(value="inferred") + logger = logging.getLogger("mobilerun") + monkeypatch.setattr(logger, "propagate", True) + answer_text = '{"value": "", "private input": true}' + with caplog.at_level(logging.DEBUG, logger="mobilerun"): + result, predict = run_agent(answer_text, inferred) + + assert result == { + "structured_output": inferred, + "success": True, + "error_message": "", + } + predict.assert_awaited_once() + debug_messages = [ + r.getMessage() for r in caplog.records if r.levelno == logging.DEBUG + ] + assert any("PydanticSerializationError" in message for message in debug_messages) + assert "private exception text" not in caplog.text + assert "private input" not in caplog.text + + +def test_llm_extraction_error_reports_failure(run_agent): + result, predict = run_agent( + "Not JSON", model=StructuredOutput, error=TypeError("extractor failed") + ) + + assert result == { + "structured_output": None, + "success": False, + "error_message": "extractor failed", + } + assert predict.await_count == 3