Spaces:
Running on T4
Running on T4
Download AI-coach-agent/src/ai_coach/input_builder.py from modventures/baseball-engine: direct link, hf CLI and curl.
- Browser
- Download file 14.8 kB
-
https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/AI-coach-agent/src/ai_coach/input_builder.py
- Command line
-
hf download hf://spaces/modventures/baseball-engine/AI-coach-agent/src/ai_coach/input_builder.py
-
curl -L -o input_builder.py https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/AI-coach-agent/src/ai_coach/input_builder.py
14.8 kB
| """Pipeline measurements -> compact CoachInput (the token saver, and the privacy and injection boundary). | |
| The pipeline sends MEASUREMENTS ONLY (see docs/AGENT_INPUT_SPEC.md). This module adds the agent's own knowledge (typical | |
| ranges for the level, which problems the repeated measurements support, the drills it may recommend) and compacts everything | |
| to a few hundred tokens. Anything the pipeline sends about faults, a priority fix, drills, ranges or advice is ignored: | |
| deciding those is the agent's job. | |
| What reaches the model, and how each part is made safe: | |
| * numbers and enum values: validated here; metric keys must be known to the agent, units come from the agent's own data; | |
| * metric notes: never forwarded. They are mapped to a short fixed vocabulary (anything else becomes "see pipeline note"); | |
| * text from the agent's own knowledge files (problem copy, drills, labels): trusted; | |
| * arm-care facts: trusted app text, validated (numbers, ISO date) and length-capped, with links, emails and phone numbers | |
| removed. They are repeated to the player, never advised on. | |
| Malformed input of any shape raises InputError (never another exception type): bad input is a caller bug. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import logging | |
| import math | |
| import re | |
| from collections.abc import Mapping | |
| from datetime import date | |
| from typing import Any | |
| from pydantic import ValidationError | |
| from . import knowledge as kb | |
| from .analysis import Analysis, analyze | |
| from .schemas import ( | |
| ArmCareInput, | |
| CaptureInput, | |
| CoachInput, | |
| DrillInput, | |
| MetricInput, | |
| ProblemInput, | |
| ) | |
| from .text_metrics import EMAIL, PHONE, URL, normalize_text | |
| log = logging.getLogger(__name__) | |
| CONFIDENCES = {"high", "medium", "est"} | |
| HIGH_SPEED_FPS, OK_FPS = 120.0, 60.0 | |
| MAX_DRILLS_PER_PROBLEM = 3 | |
| MAX_FREE_TEXT = 140 | |
| KEY_PATTERN = re.compile(r"^[a-z0-9_]{1,48}$") | |
| IGNORED_PIPELINE_KEYS = ("faults", "focus", "also_noticed", "drill", "feedback", "coach_flags", "retest", "consistency") | |
| _SPACES = re.compile(r"\s+") | |
| # The only metric "notes" the model ever sees. Pipeline free text is matched against these patterns and replaced. | |
| NOTE_VOCABULARY = ( | |
| (re.compile(r"fps|frame rate|frames per second|too slow|timing needs", re.IGNORECASE), "timing needs a higher frame rate"), | |
| (re.compile(r"implausible|out of bounds|outside the plausible", re.IGNORECASE), "value outside the plausible range"), | |
| ( | |
| re.compile(r"not computed|not found|missing|could not|unavailable|no event", re.IGNORECASE), | |
| "not computed: a key event was not found", | |
| ), | |
| (re.compile(r"capped|event timing", re.IGNORECASE), "limited by event timing"), | |
| (re.compile(r"hidden|below floor|quality|low confidence", re.IGNORECASE), "measurement quality too low"), | |
| (re.compile(r"estimate", re.IGNORECASE), "estimate only"), | |
| ) | |
| GENERIC_NOTE = "see pipeline note" | |
| IMPLAUSIBLE_NOTE = "value outside the plausible range" | |
| class InputError(ValueError): | |
| """The session JSON is missing required parts or has invalid measurements.""" | |
| def sanitise_text(text: Any, limit: int = MAX_FREE_TEXT) -> str | None: | |
| """One-line, length-capped text with links, emails and phone numbers removed. | |
| This is NOT a defence against instructions written in plain words: untrusted text (metric notes) is never forwarded at | |
| all (see `safe_note`), and the only free text that is, arm-care facts, comes from the app and is only ever repeated. | |
| """ | |
| if text is None: | |
| return None | |
| cleaned = PHONE.sub("[removed]", EMAIL.sub("[removed]", URL.sub("[removed]", normalize_text(str(text))))) | |
| cleaned = _SPACES.sub(" ", cleaned).strip() | |
| return cleaned[:limit] or None | |
| def safe_note(raw: str | None) -> str | None: | |
| """Replace a pipeline note with a phrase from the fixed vocabulary, so no untrusted text can reach the model.""" | |
| if raw is None: | |
| return None | |
| text = normalize_text(raw) | |
| return next((phrase for pattern, phrase in NOTE_VOCABULARY if pattern.search(text)), GENERIC_NOTE) | |
| def fps_class(fps: float | None) -> str: | |
| if not fps or fps <= 0: | |
| return "unknown" | |
| if fps >= HIGH_SPEED_FPS: | |
| return "high_speed" | |
| return "ok" if fps >= OK_FPS else "low" | |
| def _known_capture_reasons() -> set[str]: | |
| return set(kb._load("bounds.yaml")["capture_reasons"]) | |
| def _capture(raw: Any) -> CaptureInput: | |
| if not isinstance(raw, Mapping) or "ok" not in raw: | |
| raise InputError("capture.ok is required") | |
| reasons = raw.get("reasons", []) | |
| if not isinstance(reasons, list): | |
| raise InputError("capture.reasons must be a list of reason keys") | |
| known = _known_capture_reasons() | |
| kept = [r for r in reasons if isinstance(r, str) and r in known] | |
| if len(kept) != len(reasons): | |
| log.warning("dropped unknown capture reasons: %s", [r for r in reasons if r not in known]) | |
| return CaptureInput(ok=bool(raw["ok"]), reasons=kept) | |
| def _count(name: str, value: Any) -> int | None: | |
| if value is None: | |
| return None | |
| bad = isinstance(value, bool) or not isinstance(value, int | float) or not math.isfinite(value) or value < 0 | |
| if bad or value != int(value): | |
| raise InputError(f"arm_care.{name} must be a non-negative whole number, got {value!r}") | |
| return int(value) | |
| def _arm_care(raw: Any) -> ArmCareInput | None: | |
| """Pitch-count facts come from the app, not the pipeline, and are only ever repeated.""" | |
| if raw is None: | |
| return None | |
| if not isinstance(raw, Mapping): | |
| raise InputError("arm_care must be an object") | |
| if not raw.get("known", True): | |
| return None | |
| next_date = raw.get("next_eligible_date") | |
| if next_date is not None: | |
| try: | |
| next_date = date.fromisoformat(str(next_date)[:10]).isoformat() | |
| except ValueError as exc: | |
| raise InputError(f"arm_care.next_eligible_date must be an ISO date, got {raw.get('next_eligible_date')!r}") from exc | |
| alerts = raw.get("alerts") or [] | |
| if not isinstance(alerts, list): | |
| raise InputError("arm_care.alerts must be a list") | |
| fatigue = raw.get("fatigue_watch") or {} | |
| if not isinstance(fatigue, Mapping): | |
| raise InputError("arm_care.fatigue_watch must be an object") | |
| texts = [sanitise_text(a.get("message") if isinstance(a, Mapping) else a) for a in alerts] | |
| return ArmCareInput( | |
| pitch_count_today=_count("pitch_count_today", raw.get("pitch_count_today")), | |
| daily_max=_count("daily_max", raw.get("daily_max")), | |
| next_eligible_date=next_date, | |
| alerts=[t for t in texts if t], | |
| mechanics_drift=sanitise_text(fatigue.get("message")), | |
| ) | |
| def _clean_metric(discipline: str, i: int, m: Any, bounds: dict, known: set[str], seen: set[str], unknown: set[str]): | |
| """One validated metric dict, or None when it is dropped (unknown key, duplicate).""" | |
| if not isinstance(m, Mapping) or not isinstance(m.get("key"), str): | |
| raise InputError(f"rep {i}: every metric needs a text key") | |
| key = m["key"] | |
| if m.get("confidence", "est") not in CONFIDENCES: | |
| raise InputError(f"rep {i} {key[:48]}: confidence must be high|medium|est, got {m.get('confidence')!r}") | |
| value = m.get("value") | |
| if value is not None and (not isinstance(value, int | float) or isinstance(value, bool) or not math.isfinite(value)): | |
| raise InputError(f"rep {i} {key[:48]}: value must be a finite number or null, got {value!r}") | |
| for field in ("unit", "note"): | |
| if m.get(field) is not None and not isinstance(m[field], str): | |
| raise InputError(f"rep {i} {key[:48]}: {field} must be text or null") | |
| if not KEY_PATTERN.match(key) or key not in known: | |
| unknown.add(key[:48]) | |
| return None | |
| if key in seen: | |
| log.warning("rep %s sends metric %s twice; using the first", i, key) | |
| return None | |
| seen.add(key) | |
| confidence, note = m.get("confidence", "est"), safe_note(m.get("note")) | |
| if value is not None and key in bounds and not bounds[key][0] <= value <= bounds[key][1]: | |
| log.warning("rep %s %s=%s is outside the plausible range %s; treated as not measured", i, key, value, bounds[key]) | |
| value, confidence, note = None, "est", IMPLAUSIBLE_NOTE | |
| return {"key": key, "value": value, "unit": kb.metric_unit(discipline, key), "confidence": confidence, "note": note} | |
| def _clean_reps(discipline: str, reps: Any) -> list[dict[str, Any]]: | |
| """Validate every shape, drop unknown metrics and duplicates, null implausible values, fix units and notes.""" | |
| if not isinstance(reps, list): | |
| raise InputError("reps must be a list") | |
| known = set(kb.metric_keys(discipline)) | |
| bounds = kb._load("bounds.yaml")[discipline] | |
| cleaned: list[dict[str, Any]] = [] | |
| unknown: set[str] = set() | |
| for i, rep in enumerate(reps): | |
| if not isinstance(rep, Mapping): | |
| raise InputError(f"rep {i} must be an object") | |
| metrics = rep.get("metrics", []) | |
| if not isinstance(metrics, list): | |
| raise InputError(f"rep {i}: metrics must be a list") | |
| seen: set[str] = set() | |
| out = [c for m in metrics if (c := _clean_metric(discipline, i, m, bounds, known, seen, unknown)) is not None] | |
| cleaned.append({"metrics": out}) | |
| if unknown: | |
| log.warning("ignored metrics the agent does not know: %s", sorted(unknown)) | |
| return cleaned | |
| def _validate_overrides(overrides: Mapping[str, Any] | None) -> dict[str, tuple[float, float]] | None: | |
| if overrides is None: | |
| return None | |
| if not isinstance(overrides, Mapping): | |
| raise InputError("range_overrides must be a mapping of metric key to (low, high)") | |
| try: | |
| return {str(k): kb._check_override(str(k), v) for k, v in overrides.items()} | |
| except ValueError as exc: | |
| raise InputError(str(exc)) from exc | |
| def _problems(analysis: Analysis) -> list[ProblemInput]: | |
| out = [] | |
| for p in analysis.eligible: | |
| info = kb.problem_info(analysis.discipline, p.key) | |
| drills = kb.drills_for(analysis.discipline, p.key)[:MAX_DRILLS_PER_PROBLEM] | |
| out.append( | |
| ProblemInput( | |
| key=p.key, | |
| label=p.label, | |
| what=info["what"], | |
| why=info["why"], | |
| cue=info["cue"], | |
| severity=p.severity, | |
| frequency=p.frequency, | |
| reps_showing=p.reps_showing, | |
| reps_evaluated=p.reps_evaluated, | |
| median_excess=p.median_excess, | |
| evidence=p.evidence, | |
| baseline_rank=p.rank, | |
| range_confidence=p.range_confidence, | |
| drills=[DrillInput(name=d["name"], rep_scheme=d["rep_scheme"], cue=d["cue"]) for d in drills], | |
| ) | |
| ) | |
| return out | |
| def _ranges_provisional(metrics: list[MetricInput]) -> bool: | |
| """True when any range the note relies on is unverified or rough (calibrated on few athletes), or there is none.""" | |
| judged = [m for m in metrics if m.zone in ("in_range", "outside_typical_range")] | |
| if not judged: | |
| return True | |
| return any(m.range_status in ("unverified", None) or m.range_confidence == "low" for m in judged) | |
| def build_coach_input( | |
| session: Mapping[str, Any], | |
| level: str | None = None, | |
| range_overrides: Mapping[str, tuple[float, float]] | None = None, | |
| ) -> CoachInput: | |
| """Compact a session of measurements. `level` falls back to session['level']; a coach/org may override ranges. | |
| Accepts the v2 shape (measurements only). Older files that wrapped results in a `session` block, or carried faults, | |
| a focus or drills, are still read; those extras are ignored. Raises InputError (only) for malformed input. | |
| """ | |
| if not isinstance(session, Mapping): | |
| raise InputError("session must be an object") | |
| try: | |
| return _build(session, level, range_overrides) | |
| except InputError: | |
| raise | |
| except (TypeError, ValueError, KeyError, AttributeError, ValidationError) as exc: | |
| raise InputError(f"malformed session: {type(exc).__name__}: {str(exc)[:160]}") from exc | |
| def _build(session: Mapping[str, Any], level: str | None, range_overrides: Mapping[str, Any] | None) -> CoachInput: | |
| for key in ("discipline", "reps"): | |
| if key not in session: | |
| raise InputError(f"session JSON is missing {key!r}") | |
| discipline = session["discipline"] | |
| if discipline not in ("hitting", "pitching"): | |
| raise InputError(f"discipline must be hitting or pitching, got {discipline!r}") | |
| reps = _clean_reps(discipline, session["reps"]) | |
| overrides = _validate_overrides(range_overrides) | |
| block = session.get("session") if isinstance(session.get("session"), Mapping) else {} | |
| ignored = [k for k in IGNORED_PIPELINE_KEYS if k in session or k in block] | |
| if ignored: | |
| log.warning("ignoring pipeline fields %s: the agent decides problems, priority and drills itself", ignored) | |
| given_level = level if isinstance(level, str) else session.get("level") | |
| analysis = analyze(discipline, given_level if isinstance(given_level, str) else None, reps, overrides) | |
| capture = _capture(session.get("capture") if "capture" in session else block.get("capture")) | |
| metrics = [ | |
| MetricInput( | |
| key=m.key, | |
| label=m.label, | |
| value=m.value, | |
| unit=m.unit, | |
| confidence=m.confidence, | |
| band=m.band, | |
| zone=m.zone, | |
| n_reps=m.n_reps, | |
| per_rep=m.per_rep, | |
| range_status=m.range_status, | |
| range_confidence=m.range_confidence, | |
| note=m.note, | |
| ) | |
| for m in analysis.metrics | |
| ] | |
| fps = session.get("fps") | |
| fps = float(fps) if isinstance(fps, int | float) and not isinstance(fps, bool) and math.isfinite(fps) and fps > 0 else None | |
| arm_raw = session.get("arm_care") if "arm_care" in session else block.get("arm_care") | |
| return CoachInput( | |
| discipline=discipline, | |
| level=analysis.level, | |
| level_assumed=analysis.level_assumed, | |
| fps=fps, | |
| fps_class=fps_class(fps), | |
| reps_analyzed=len(reps), | |
| capture=capture, | |
| metrics=metrics, | |
| problems=_problems(analysis) if capture.ok else [], | |
| arm_care=_arm_care(arm_raw) if discipline == "pitching" else None, | |
| ranges_provisional=_ranges_provisional(metrics), | |
| ) | |
| def canonical_json(coach_input: CoachInput) -> str: | |
| """Stable, compact JSON (sorted keys, no nulls) used for the prompt and the cache key.""" | |
| data = coach_input.model_dump(mode="json", exclude_none=True) | |
| return json.dumps(data, sort_keys=True, separators=(",", ":"), ensure_ascii=False) | |
| def estimate_tokens(text: str) -> int: | |
| """Cheap token estimate (~4 characters per token) for budgets and tests; real counts come from the API.""" | |
| return max(1, len(text) // 4) | |