File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change 14
14
15
15
"""Utils for M3A."""
16
16
17
+ import ast
17
18
import base64
19
+ import json
18
20
import math
19
21
import re
20
22
from typing import Any , Optional
@@ -268,9 +270,37 @@ def parse_reason_action_output(
268
270
r'Action:(.*)' , raw_reason_action_output , flags = re .DOTALL
269
271
)
270
272
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
+
271
278
return reason , action
272
279
273
280
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
+
274
304
def _generate_screenshot_table (task_result : dict [str , Any ], i : int ) -> str :
275
305
"""Generate html string for the screenshot analysis table.
276
306
You can’t perform that action at this time.
0 commit comments