Best-effort JSON formatter tolerant to fenced blocks and noisy text.
| 7 | from .base import StatelessFormatter |
| 8 | |
| 9 | class LenientJsonMessageFormatter(StatelessFormatter): |
| 10 | """Best-effort JSON formatter tolerant to fenced blocks and noisy text.""" |
| 11 | |
| 12 | def __init__(self): |
| 13 | super().__init__() |
| 14 | self._is_input_formatter = True |
| 15 | self._is_output_formatter = True |
| 16 | self._agent_introducer = """ |
| 17 | !IMPORTANT!:Your response must contain a single JSON object. Avoid extra text. If you must, wrap the JSON in a ```json code block. |
| 18 | """ |
| 19 | |
| 20 | def format(self, message: str) -> dict: # type: ignore[override] |
| 21 | """Parse one JSON object from possibly noisy model output.""" |
| 22 | # Remove <think>...</think> tags and their content. |
| 23 | if isinstance(message, str): |
| 24 | message = re.sub(r"<think>.*?</think>", "", message, flags=re.DOTALL).strip() |
| 25 | |
| 26 | if isinstance(message, dict): |
| 27 | return message |
| 28 | |
| 29 | if not isinstance(message, str): |
| 30 | message = str(message) |
| 31 | |
| 32 | candidates: list[str] = [] |
| 33 | |
| 34 | # Prefer fenced JSON blocks when present. |
| 35 | for m in re.finditer(r"```(?:json)?\s*(.*?)```", message, flags=re.DOTALL | re.IGNORECASE): |
| 36 | inner = (m.group(1) or "").strip() |
| 37 | if inner: |
| 38 | candidates.append(inner) |
| 39 | |
| 40 | # Fallback: take the widest {...} span. |
| 41 | start = message.find("{") |
| 42 | end = message.rfind("}") |
| 43 | if start != -1 and end != -1 and end > start: |
| 44 | candidates.append(message[start : end + 1].strip()) |
| 45 | |
| 46 | # Last resort: try the whole message. |
| 47 | candidates.append(message.strip()) |
| 48 | |
| 49 | last_error: Exception | None = None |
| 50 | for cand in candidates: |
| 51 | if not cand: |
| 52 | continue |
| 53 | try: |
| 54 | parsed = json.loads(cand) |
| 55 | except Exception as e: |
| 56 | last_error = e |
| 57 | try: |
| 58 | parsed = ast.literal_eval(cand) |
| 59 | except Exception as e2: |
| 60 | last_error = e2 |
| 61 | continue |
| 62 | if isinstance(parsed, dict): |
| 63 | return parsed |
| 64 | |
| 65 | raise ValueError(f"LenientJsonMessageFormatter: failed to parse JSON object: {last_error}") |
| 66 |
no outgoing calls
no test coverage detected