Parse JSON/Python-like structured output into a Python object.
(value: Any)
| 175 | |
| 176 | |
| 177 | def parse_structured_answer(value: Any) -> Any: |
| 178 | """Parse JSON/Python-like structured output into a Python object.""" |
| 179 | if isinstance(value, (dict, list, tuple, int, float, bool)) or value is None: |
| 180 | return value |
| 181 | |
| 182 | content = extract_answer_text(value) |
| 183 | content = _strip_markdown_fence(content) |
| 184 | |
| 185 | count = _extract_count_from_text(content) |
| 186 | if count is not None: |
| 187 | return count |
| 188 | |
| 189 | content = _extract_balanced_structure(content) |
| 190 | |
| 191 | try: |
| 192 | return json.loads(content) |
| 193 | except json.JSONDecodeError: |
| 194 | pass |
| 195 | |
| 196 | try: |
| 197 | return ast.literal_eval(content) |
| 198 | except (ValueError, SyntaxError): |
| 199 | pass |
| 200 | |
| 201 | try: |
| 202 | return json.loads(content.replace("'", '"')) |
| 203 | except json.JSONDecodeError: |
| 204 | pass |
| 205 | |
| 206 | count = _extract_count_from_text(content) |
| 207 | if count is not None: |
| 208 | return count |
| 209 | |
| 210 | return content.strip() |
| 211 | |
| 212 | |
| 213 | def normalize_value(value: Any) -> str: |