| from __future__ import annotations |
|
|
| import json |
| from typing import Any |
|
|
|
|
| def extract_tool_actions(text: str) -> list[dict[str, Any]]: |
| parsed = extract_json_value(text) |
| if isinstance(parsed, dict): |
| if "actions" in parsed: |
| raw_actions = parsed["actions"] |
| elif "tool_calls" in parsed: |
| raw_actions = parsed["tool_calls"] |
| else: |
| raw_actions = [parsed] |
| elif isinstance(parsed, list): |
| raw_actions = parsed |
| else: |
| raise ValueError("tool call JSON must be an object or array") |
|
|
| if not isinstance(raw_actions, list) or not raw_actions: |
| raise ValueError("actions must be a non-empty array") |
|
|
| actions: list[dict[str, Any]] = [] |
| for index, raw_action in enumerate(raw_actions, start=1): |
| if not isinstance(raw_action, dict): |
| raise ValueError(f"action #{index} must be an object") |
| actions.append(normalize_tool_action(raw_action)) |
| return actions |
|
|
|
|
| def normalize_tool_action(raw_action: dict[str, Any]) -> dict[str, Any]: |
| if "function" in raw_action and isinstance(raw_action["function"], dict): |
| function = raw_action["function"] |
| return normalize_named_tool_action(function.get("name"), function.get("arguments", {})) |
| if "tool" in raw_action or "name" in raw_action: |
| return normalize_named_tool_action( |
| raw_action.get("tool", raw_action.get("name")), |
| raw_action.get("arguments", {}), |
| ) |
| if "action" in raw_action: |
| return dict(raw_action) |
| raise ValueError("action object must contain 'tool', 'name', 'function', or 'action'") |
|
|
|
|
| def normalize_named_tool_action(name: Any, arguments: Any) -> dict[str, Any]: |
| if not isinstance(name, str) or not name.strip(): |
| raise ValueError("tool name must be a non-empty string") |
| if isinstance(arguments, str): |
| try: |
| arguments = json.loads(arguments) if arguments.strip() else {} |
| except json.JSONDecodeError as exc: |
| raise ValueError(f"tool arguments are not valid JSON: {exc}") from exc |
| if arguments is None: |
| arguments = {} |
| if not isinstance(arguments, dict): |
| raise ValueError("tool arguments must be an object") |
| action = dict(arguments) |
| action["action"] = name.strip() |
| return action |
|
|
|
|
| def extract_json_value(text: str) -> Any: |
| stripped = strip_code_fence(text.strip()) |
| try: |
| return json.loads(stripped) |
| except json.JSONDecodeError: |
| return json.loads(find_first_json_value(stripped)) |
|
|
|
|
| def strip_code_fence(text: str) -> str: |
| if not text.startswith("```"): |
| return text |
| lines = text.splitlines() |
| if len(lines) >= 3 and lines[-1].strip() == "```": |
| return "\n".join(lines[1:-1]).strip() |
| return text |
|
|
|
|
| def find_first_json_value(text: str) -> str: |
| object_start = text.find("{") |
| array_start = text.find("[") |
| starts = [index for index in (object_start, array_start) if index != -1] |
| if not starts: |
| raise ValueError("no JSON object or array found") |
| start = min(starts) |
| opening = text[start] |
| closing = "}" if opening == "{" else "]" |
|
|
| depth = 0 |
| in_string = False |
| escaped = False |
| for index in range(start, len(text)): |
| char = text[index] |
| if in_string: |
| if escaped: |
| escaped = False |
| elif char == "\\": |
| escaped = True |
| elif char == '"': |
| in_string = False |
| continue |
|
|
| if char == '"': |
| in_string = True |
| elif char == opening: |
| depth += 1 |
| elif char == closing: |
| depth -= 1 |
| if depth == 0: |
| return text[start : index + 1] |
| raise ValueError("unterminated JSON value") |
|
|