repositories
loading repo index
repositories
loading repo index
repository
loading code, commits, and activity
Mirrored from https://github.com/yingqi-z20/Agent-libOS
stars
latest
clone command
git clone gitlawb://did:key:z6MkqRzA...RfoM/yingqi-z20-Agen...git clone gitlawb://did:key:z6MkqRzA.../yingqi-z20-Agen...d98dd2c9IPC1d ago| #1 | from __future__ import annotations |
| #2 | |
| #3 | import json |
| #4 | from typing import Any |
| #5 | |
| #6 | |
| #7 | def parse_json_action(text: str) -> dict[str, Any]: |
| #8 | stripped = text.strip() |
| #9 | if stripped.startswith("```"): |
| #10 | stripped = _strip_fence(stripped) |
| #11 | try: |
| #12 | value = json.loads(stripped) |
| #13 | except json.JSONDecodeError: |
| #14 | value = json.loads(_extract_last_action_object(stripped)) |
| #15 | if not isinstance(value, dict): |
| #16 | raise ValueError("LLM action must be a JSON object") |
| #17 | if "action" not in value: |
| #18 | raise ValueError("LLM action missing 'action'") |
| #19 | return value |
| #20 | |
| #21 | |
| #22 | def _strip_fence(text: str) -> str: |
| #23 | lines = text.splitlines() |
| #24 | if lines and lines[0].startswith("```"): |
| #25 | lines = lines[1:] |
| #26 | if lines and lines[-1].startswith("```"): |
| #27 | lines = lines[:-1] |
| #28 | return "\n".join(lines).strip() |
| #29 | |
| #30 | |
| #31 | def _extract_last_action_object(text: str) -> str: |
| #32 | candidates = _extract_json_objects(text) |
| #33 | for candidate in reversed(candidates): |
| #34 | try: |
| #35 | value = json.loads(candidate) |
| #36 | except json.JSONDecodeError: |
| #37 | continue |
| #38 | if isinstance(value, dict) and "action" in value: |
| #39 | return candidate |
| #40 | raise ValueError("no JSON action object found") |
| #41 | |
| #42 | |
| #43 | def _extract_json_objects(text: str) -> list[str]: |
| #44 | objects: list[str] = [] |
| #45 | start: int | None = None |
| #46 | depth = 0 |
| #47 | in_string = False |
| #48 | escaped = False |
| #49 | for index, char in enumerate(text): |
| #50 | if in_string: |
| #51 | if escaped: |
| #52 | escaped = False |
| #53 | elif char == "\\": |
| #54 | escaped = True |
| #55 | elif char == '"': |
| #56 | in_string = False |
| #57 | continue |
| #58 | if char == '"': |
| #59 | in_string = True |
| #60 | elif char == "{": |
| #61 | if depth == 0: |
| #62 | start = index |
| #63 | depth += 1 |
| #64 | elif char == "}" and depth: |
| #65 | depth -= 1 |
| #66 | if depth == 0 and start is not None: |
| #67 | objects.append(text[start : index + 1]) |
| #68 | start = None |
| #69 | return objects |
| #70 |