Skip to content

Commit d204160

Browse files
author
The android_world Authors
committed
Extract json after parsing action str as LLM may put extra stuff, such as ```, around the curly brackets.
PiperOrigin-RevId: 718042490
1 parent ca16d3d commit d204160

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

android_world/agents/m3a_utils.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,9 @@
1414

1515
"""Utils for M3A."""
1616

17+
import ast
1718
import base64
19+
import json
1820
import math
1921
import re
2022
from typing import Any, Optional
@@ -268,9 +270,37 @@ def parse_reason_action_output(
268270
r'Action:(.*)', raw_reason_action_output, flags=re.DOTALL
269271
)
270272
action = action_result.group(1).strip() if action_result else None
273+
if action:
274+
extracted = extract_json(action)
275+
if extracted is not None:
276+
action = json.dumps(extracted)
277+
271278
return reason, action
272279

273280

281+
def extract_json(s: str) -> Optional[dict[str, Any]]:
282+
"""Extracts JSON from string.
283+
284+
Args:
285+
s: A string with a JSON in it. E.g., "{'hello': 'world'}" or from CoT:
286+
"let's think step-by-step, ..., {'hello': 'world'}".
287+
288+
Returns:
289+
JSON object.
290+
"""
291+
pattern = r'\{.*?\}'
292+
match = re.search(pattern, s, re.DOTALL)
293+
if match:
294+
try:
295+
return ast.literal_eval(match.group())
296+
except (SyntaxError, ValueError) as error:
297+
print(f'Cannot extract JSON, skipping due to error {error}')
298+
return None
299+
else:
300+
print(f'No JSON match in {s}')
301+
return None
302+
303+
274304
def _generate_screenshot_table(task_result: dict[str, Any], i: int) -> str:
275305
"""Generate html string for the screenshot analysis table.
276306

0 commit comments

Comments
 (0)