Parse action from model response. Args: response: Raw response string from the model. Returns: Parsed action dictionary. Raises: ValueError: If the response cannot be parsed.
(response: str)
| 330 | |
| 331 | |
| 332 | def parse_action(response: str) -> dict[str, Any]: |
| 333 | """ |
| 334 | Parse action from model response. |
| 335 | |
| 336 | Args: |
| 337 | response: Raw response string from the model. |
| 338 | |
| 339 | Returns: |
| 340 | Parsed action dictionary. |
| 341 | |
| 342 | Raises: |
| 343 | ValueError: If the response cannot be parsed. |
| 344 | """ |
| 345 | print(f"Parsing action: {response}") |
| 346 | try: |
| 347 | response = response.strip() |
| 348 | if response.startswith('do(action="Type"') or response.startswith( |
| 349 | 'do(action="Type_Name"' |
| 350 | ): |
| 351 | text = response.split("text=", 1)[1][1:-2] |
| 352 | action = {"_metadata": "do", "action": "Type", "text": text} |
| 353 | return action |
| 354 | elif response.startswith("do"): |
| 355 | # Use AST parsing instead of eval for safety |
| 356 | try: |
| 357 | # Escape special characters (newlines, tabs, etc.) for valid Python syntax |
| 358 | response = response.replace('\n', '\\n') |
| 359 | response = response.replace('\r', '\\r') |
| 360 | response = response.replace('\t', '\\t') |
| 361 | |
| 362 | tree = ast.parse(response, mode="eval") |
| 363 | if not isinstance(tree.body, ast.Call): |
| 364 | raise ValueError("Expected a function call") |
| 365 | |
| 366 | call = tree.body |
| 367 | # Extract keyword arguments safely |
| 368 | action = {"_metadata": "do"} |
| 369 | for keyword in call.keywords: |
| 370 | key = keyword.arg |
| 371 | value = ast.literal_eval(keyword.value) |
| 372 | action[key] = value |
| 373 | |
| 374 | return action |
| 375 | except (SyntaxError, ValueError) as e: |
| 376 | raise ValueError(f"Failed to parse do() action: {e}") |
| 377 | |
| 378 | elif response.startswith("finish"): |
| 379 | action = { |
| 380 | "_metadata": "finish", |
| 381 | "message": response.replace("finish(message=", "")[1:-2], |
| 382 | } |
| 383 | else: |
| 384 | raise ValueError(f"Failed to parse action: {response}") |
| 385 | return action |
| 386 | except Exception as e: |
| 387 | raise ValueError(f"Failed to parse action: {e}") |
| 388 | |
| 389 |
no outgoing calls
no test coverage detected