Repository navigation
fix(structured-output): skip LLM extraction when the final answer is valid JSON (DRO-4207) #560
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
df2c422
cf606b5
4438c73
333de61
5fbf19b
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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, | ||
|
|
@@ -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( | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 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: | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 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") | ||
|
|
||
|
|
||
There was a problem hiding this comment.
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 withdarkModeEnabled=nulland made zero extractor calls. Line 93 counts thesettingsobject as non-null even though its only field is null. I also reproduced this with a PydanticAliasPathwhenmessagesits beside the null field insidesettings.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.