trainhiro-sdk 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of trainhiro-sdk might be problematic. Click here for more details.

trainhiro/_util.py ADDED
@@ -0,0 +1,103 @@
1
+ """Internal helpers: JSON-safe conversion and rate-limited logging. Not public API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import logging
7
+ import math
8
+ import threading
9
+ import time
10
+ from collections.abc import Mapping
11
+ from typing import Any
12
+
13
+ logger = logging.getLogger("trainhiro")
14
+
15
+ _DROP = object() # marker: omit this value (provider "not given" sentinels)
16
+ _SENTINEL_TYPES = frozenset({"Omit", "NotGiven"})
17
+ _MAX_DEPTH = 64
18
+
19
+
20
+ def _is_sentinel(value: Any) -> bool:
21
+ return type(value).__name__ in _SENTINEL_TYPES
22
+
23
+
24
+ def to_jsonable(value: Any, _depth: int = 0) -> Any:
25
+ """Convert ``value`` to plain JSON types without ever raising.
26
+
27
+ Pydantic models (provider request/response objects) are dumped with
28
+ ``exclude_none``; ``Omit``/``NotGiven`` sentinels are dropped from mappings
29
+ and lists; anything else unknown becomes its ``repr``. Non-finite floats
30
+ become strings so the span stays valid JSON.
31
+ """
32
+ try:
33
+ return _convert(value, _depth)
34
+ except Exception: # pragma: no cover - defensive
35
+ return f"<unserializable {type(value).__name__}>"
36
+
37
+
38
+ def _convert(value: Any, depth: int) -> Any:
39
+ if depth > _MAX_DEPTH:
40
+ return "<max depth>"
41
+ if value is None or isinstance(value, (str, bool, int)):
42
+ return value
43
+ if isinstance(value, float):
44
+ return value if math.isfinite(value) else repr(value)
45
+ if _is_sentinel(value):
46
+ return _DROP
47
+ if isinstance(value, Mapping):
48
+ out: dict[str, Any] = {}
49
+ for k, v in value.items():
50
+ c = _convert(v, depth + 1)
51
+ if c is not _DROP:
52
+ out[str(k)] = c
53
+ return out
54
+ if isinstance(value, (list, tuple, set, frozenset)):
55
+ return [c for c in (_convert(v, depth + 1) for v in value) if c is not _DROP]
56
+ if isinstance(value, (bytes, bytearray)):
57
+ return f"<{len(value)} bytes>"
58
+ if isinstance(value, type):
59
+ return f"{value.__module__}.{value.__qualname__}"
60
+ dump = getattr(value, "model_dump", None)
61
+ if callable(dump):
62
+ try:
63
+ return _convert(dump(mode="json", exclude_none=True), depth + 1)
64
+ except Exception:
65
+ pass
66
+ return repr(value)
67
+
68
+
69
+ def parse_json_arguments(raw: Any) -> Any:
70
+ """Tool-call arguments: the parsed JSON value when possible, else the raw value."""
71
+ if isinstance(raw, str):
72
+ try:
73
+ return json.loads(raw)
74
+ except ValueError:
75
+ return raw
76
+ return to_jsonable(raw)
77
+
78
+
79
+ def as_token_count(value: Any) -> int | None:
80
+ if isinstance(value, bool) or not isinstance(value, int) or value < 0:
81
+ return None
82
+ return value
83
+
84
+
85
+ class RateLimitedLog:
86
+ """Log a warning at most once per ``interval`` seconds per key (export failures can be hot)."""
87
+
88
+ def __init__(self, interval: float = 60.0) -> None:
89
+ self._interval = interval
90
+ self._last: dict[str, float] = {}
91
+ self._lock = threading.Lock()
92
+
93
+ def warning(self, key: str, msg: str, *args: Any) -> None:
94
+ now = time.monotonic()
95
+ with self._lock:
96
+ last = self._last.get(key)
97
+ if last is not None and now - last < self._interval:
98
+ return
99
+ self._last[key] = now
100
+ logger.warning(msg, *args)
101
+
102
+
103
+ warn_limited = RateLimitedLog()