Bhuminjay's picture
PermitForge OpenEnv Space at attoloop/PermitForge 03a9851
ce5d968 verified
Raw History Blame Contribute Delete
2.98 kB
"""JSON boundary shared by tools and episode records."""
from decimal import Decimal
import json
import math
from typing import Any
MAX_SOURCES = 6
MAX_KEY_LENGTH = 64
MAX_DESIGN_BYTES = 4096
def design_size_ok(design: Any) -> bool:
"""Reject oversized or deeply nested data before validation or record copying."""
if not isinstance(design, dict):
return design is None or isinstance(design, (bool, int, float)) or design == []
if len(design) > MAX_SOURCES:
return False
for sid, row in design.items():
if not isinstance(sid, str) or len(sid) > MAX_KEY_LENGTH:
return False
if not isinstance(row, dict):
return False
if len(row) > 2:
return False
for key, value in row.items():
if not isinstance(key, str) or len(key) > MAX_KEY_LENGTH:
return False
if not isinstance(value, (str, bool, int, float, Decimal, type(None))):
return False
if isinstance(value, str) and len(value) > MAX_DESIGN_BYTES:
return False
try:
return len(json.dumps(json_value(design), ensure_ascii=False).encode()) <= MAX_DESIGN_BYTES
except (ValueError, OverflowError):
return False
DESIGN_SCHEMA = {
'type': 'object',
'maxProperties': MAX_SOURCES,
'propertyNames': {'maxLength': MAX_KEY_LENGTH},
'additionalProperties': {
'type': 'object', 'additionalProperties': False,
'required': ['control', 'height_m'],
'properties': {'control': {'type': 'string'}, 'height_m': {'type': 'number'}},
},
}
def json_value(value: Any) -> Any:
if isinstance(value, Decimal):
return float(value) if value.is_finite() else str(value)
if isinstance(value, float) and not math.isfinite(value):
return str(value)
if isinstance(value, dict):
return {str(k): json_value(v) for k, v in value.items()}
if isinstance(value, (list, tuple)):
return [json_value(v) for v in value]
return value
def tool_result(observation: Any) -> dict:
if getattr(observation, 'error', None):
error = observation.error
return {'error': error.get('message') if isinstance(error, dict) else error.message}
result = observation.result
if hasattr(result, 'data') and result.data is not None:
return json.loads(result.data) if isinstance(result.data, str) else result.data
if hasattr(result, 'content'):
result = {'content': [b.model_dump() for b in result.content]}
if hasattr(result, 'model_dump'):
result = result.model_dump()
if isinstance(result, dict):
for block in result.get('content', []):
if block.get('type') == 'text':
return json.loads(block['text'])
if 'data' in result:
return json.loads(result['data']) if isinstance(result['data'], str) else result['data']
return result
return json.loads(result)