Buckets:

Hooshaai/RL_AEGIS / src /aegis /utils /formatting.py
tahamajs's picture
download
raw
2.06 kB
"""Text formatting, prompt construction, and robust JSON extraction helpers."""
import re
import json
from typing import Any, Dict, List, Optional, Union
def extract_json_payload(text: str) -> Optional[Union[Dict[str, Any], List[Any]]]:
"""Robustly extracts and parses JSON dictionary or list from arbitrary text."""
if not text or not isinstance(text, str):
return None
# 1. Try markdown code block extraction
json_block_match = re.search(r"```(?:json)?\s*([\s\S]*?)\s*```", text, re.IGNORECASE)
if json_block_match:
content = json_block_match.group(1).strip()
try:
return json.loads(content)
except Exception:
pass
# 2. Try direct parsing
try:
return json.loads(text.strip())
except Exception:
pass
# 3. Try finding outermost JSON object {...}
obj_match = re.search(r"\{[\s\S]*\}", text)
if obj_match:
try:
return json.loads(obj_match.group(0))
except Exception:
pass
# 4. Try finding outermost JSON array [...]
arr_match = re.search(r"\[[\s\S]*\]", text)
if arr_match:
try:
return json.loads(arr_match.group(0))
except Exception:
pass
return None
def normalize_verdict_str(verdict: Any) -> str:
"""Normalizes verdict string for consistent comparison."""
if verdict is None:
return ""
v_str = str(verdict).strip()
# Strip quotes or punctuation around single words
v_str = re.sub(r"^[\"']|[\"']$", "", v_str).strip()
return v_str
def format_chat_prompt(messages: List[Dict[str, str]], add_generation_prompt: bool = True) -> str:
"""Formats a list of chat messages into a standardized conversation string."""
lines = []
for msg in messages:
role = msg.get("role", "user").capitalize()
content = msg.get("content", "").strip()
lines.append(f"<{role}>\n{content}\n</{role}>")
if add_generation_prompt:
lines.append("<Assistant>\n")
return "\n\n".join(lines)

Xet Storage Details

Size:
2.06 kB
·
Xet hash:
a59e492ee33ccd89e9cb316903bd8a744e3d14d800b46af8d4f82017c230f7b6

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.