File size: 2,980 Bytes
ce5d968
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
"""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)