Skip to content
Merged
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
131 changes: 107 additions & 24 deletions mobilerun/agent/oneflows/structured_output_agent.py
Original file line number Diff line number Diff line change
@@ -1,30 +1,37 @@
"""
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

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,
Expand All @@ -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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex: [P2] Preserve the answer when recognized fields contain only nulls

With {"settings":{"darkModeEnabled":null},"message":"Dark mode enabled"}, the workflow returned success with darkModeEnabled=null and made zero extractor calls. Line 93 counts the settings object as non-null even though its only field is null. I also reproduced this with a Pydantic AliasPath when message sits beside the null field inside settings.

When the check discards input, use the recognized leaf values to decide whether to skip extraction, and account for siblings along alias paths. An explicit null with no discarded input should still take the fast path.

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(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex: [P2] Fall back when validation discards the entire answer

The documented dark-mode schema makes success and darkModeEnabled optional. With {"message":"Dark mode was successfully enabled"}, Pydantic ignores message, supplies both defaults, and the fast path reports success with {"success":null,"darkModeEnabled":null}. The original answer contains the information the extractor needs.

Please fall back when validation discards every field in a nonempty object. A regression test should also keep the fast path working when the answer supplies a recognized field alongside an ignored extra.

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:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex: [P2] Preserve extraction after input-dependent conversion errors

For an SDK output model with ratio: Fraction, Pydantic raises TypeError on {"ratio":{"numerator":1,"denominator":2}}. This handler lets that exception reach the outer failure path. I ran the same input with a stub extractor on both revisions. The base called it once and accepted the normalized "1/2" value. This revision made zero calls and returned structured_output=None.

Please route recoverable errors from direct validation or the JSON-mode dump through the existing extractor, and cover an input the extractor can normalize.

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")

Expand Down
Loading
Loading