github-actions[bot]
Automated Deploy: a36ad9fbaf2a4b4a2efb7feea50aa69986cf59d3
e980186
|
Raw History Blame Contribute Delete
9.48 kB

AI Coach Agent

Reads the measurements from the pose pipeline and writes a short, honest coaching note for a baseball player: what looks solid, what to work on (one priority fix), a cue, one drill, and caveats about data quality. The agent does the judging. The pipeline only sends numbers; the agent finds the problems the repeated measurements support, decides what matters most and explains it. Deterministic code supplies verified evidence and checks every claim; a rule-based note is the always-available fallback and the yardstick.

  • Cost: about $0.002 per note on gemini-3.1-flash-lite; $0 for repeats and for sessions with nothing to judge (see docs/MODEL_CHOICE.md).
  • Safe by construction: numbers only (never video), every problem must be backed by evidence, no invented numbers, no praise on estimates, drills only from the library, no medical language, rule-based fallback.
  • For the ML / pipeline engineer: read docs/POSE_DATA_SPEC.md then docs/AGENT_INPUT_SPEC.md (measurements only; he never sends faults, a priority fix or drills) and run python -m ai_coach.validate session.json.

Layout

src/ai_coach/
  schemas.py        CoachInput (what the agent sees) / CoachNote (what it returns) / CoachResult
  input_builder.py  measurements -> compact CoachInput; adds the agent's own ranges, problems and drills; sanitises free text
  analysis.py       deterministic evidence: per-metric stats, which problems the repeated measurements support, baseline ranking
  knowledge/        ranges.yaml (typical ranges by level), problems.yaml (14 problems + evidence rules), drills.yaml (30 drills),
                    metrics.yaml (labels, aliases), bounds.yaml (plausible values)   <- the agent's own, editable reference data
  prompts/          system.md, examples.md, user.md  (edit prompts here; the version hash changes the cache key)
  prompt_loader.py  loads + versions prompts, builds the LangChain ChatPromptTemplate
  chain.py          GeminiGenerator: prompt | ChatGoogleGenerativeAI.with_structured_output(CoachNote)
  guardrails.py     evidence-based checks (problem supported + cited, drill from library, praise rules, numbers, vocabulary, tone)
  fallback.py       deterministic rule-based note = the software baseline (always available)
  scoring.py        the 0-100 mechanics score (code, never the model)
  timing.py         load-and-timing section built by code from the engine's timing measurements
  response.py       the app-facing response v2.0 assembled from the note, score and timing
  cache.py          sqlite response cache with TTL        cost.py   usage ledger (calls + requests), prices, budget guard
  tracing.py        LangSmith tracing (explicit client)   observability.py   JSON logs, redaction   report.py   usage report
  service.py        CoachService: cache -> Gemini (repair, escalate) -> guardrails -> fallback; records agreement with the baseline
  validate.py       checks pipeline output before it reaches the coach     cli.py   command line
docs/               POSE_DATA_SPEC.md (pose points/objects/events), AGENT_INPUT_SPEC.md (measurements for the coach), OBSERVABILITY.md,
                    MODEL_CHOICE.md, *.schema.json, examples/pose_track_example.json
examples/inputs/    10 synthetic measurement sessions + 1 real clip (hitting and pitching, one and two problems, low fps, bad rep)
evals/run_eval.py   quality / cost / cache report          tools/   make_examples, export_schema, check_pose_json, import_reference_data
tests/              300+ offline tests; tests/test_live.py is opt-in

Setup

python3.11 -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"
cp .env.example .env        # then put your key in GOOGLE_API_KEY (the file is git-ignored)

Use

from ai_coach import CoachService

service = CoachService()
result = service.coach(session_json, level="hs_varsity")  # never raises for model/network problems
print(result.note.headline, result.source, result.usage.cost_usd)  # source is "llm" or "rules"
response = service.respond(session)  # what the HTTP API returns: score, summary, focus, drill, timing ...
python -m ai_coach.cli examples/inputs/hitting_overstride_240fps.json            # uses Gemini if a key is set
python -m ai_coach.cli examples/inputs/hitting_overstride_240fps.json --fallback-only
python -m ai_coach.validate examples/inputs/pitching_short_stride_240fps.json
python evals/run_eval.py --mode rules                  # offline
python evals/run_eval.py --mode live --repeat 2        # real calls; second pass shows cache hits

await service.acoach(...) is the async variant (runs the blocking call in a worker thread).

HTTP API and Docker

POST /v1/coach takes a session (and optional hitting timing) and returns the response v2.0: score, summary, strengths, focus, drill, timing, arm care and data quality (API contract, screen guide); GET /v1/usage, /healthz and /readyz too. Build and run with docker build -t ai-coach-agent .. Endpoints, auth, scaling notes and what to mount: docs/DEPLOYMENT.md.

How a note is produced

  1. input_builder takes the measurements (anything the pipeline says about faults, focus, drills or ranges is ignored), looks up the typical ranges for the player's level in the agent's own data, and analysis finds the problems the repeated, trustworthy measurements support (one bad rep is not a pattern; estimates are never evidence). Free text is sanitised.
  2. Nothing judgeable, or capture failed: rule-based note, no model call.
  3. Response cache hit (re-checked against the guardrails): return it. Otherwise one Gemini call with structured output (CoachNote).
  4. Gemini judges: it picks what looks solid, chooses ONE priority fix among the supported problems (it may differ from the software's suggested order), cites the evidence, picks a drill from the library offered for that problem and writes the caveats.
  5. guardrails.check_note must pass. If not: repair retry (same model), then one call on the escalation model, then the rule-based note.
  6. Only guardrail-clean notes are cached. Every call's tokens and cost go to the ledger, the JSON log and (if enabled) LangSmith, together with whether Gemini's priority fix agreed with the software baseline (ai-coach-report shows the agreement rate).

Usage, cost and logs

python -m ai_coach.report --days 7                 # tokens, cost, cache hit rate, fallbacks, latency, budget
python -m ai_coach.tracing check                   # verify LangSmith is connected (needs your key)
tail -f .coach_cache/logs/coach.jsonl              # one JSON line per model call and per request
  • LangSmith shows every Gemini call as a trace (prompt, output, tokens, latency) with cost_usd, attempts, fallback reason and request_id as filterable metadata. Turn it on with COACH_TRACING=true and LANGSMITH_API_KEY in .env.
  • The local ledger and JSON logs also cover cache hits and rule-based notes, enforce the daily budget, and never contain note text or session data. Full guide: docs/OBSERVABILITY.md.

Configuration (env or .env)

Variable Default Meaning
GOOGLE_API_KEY none without it the service uses rule-based notes only
COACH_MODEL / COACH_ESCALATION_MODEL gemini-3.8-flash / gemini-3.8-flash escalation only runs when it differs from the model
COACH_FALLBACK_MODEL gemini-3.5-flash-lite writes the swing report text when the model is overloaded or rate limited; empty to disable
COACH_DAILY_BUDGET_USD 5.00 stops model calls when spent
COACH_CACHE_PATH, COACH_CACHE_TTL_DAYS .coach_cache/responses.sqlite3, 30 response cache
COACH_FAILURE_CACHE_TTL_S 300 how long a rule-based outcome is remembered so identical requests do not repeat the model chain (0 = off)
COACH_TIMEOUT_S, COACH_MAX_OUTPUT_TOKENS, COACH_TEMPERATURE 20, 700, 0.2 model call limits
COACH_THINKING_LEVEL / COACH_THINKING_BUDGET unset thinking tokens are billed as output; sent only when set; verify the model accepts it
COACH_TRACING, LANGSMITH_API_KEY, LANGSMITH_PROJECT, LANGSMITH_ENDPOINT off LangSmith tracing, see docs/OBSERVABILITY.md
COACH_LOG_DIR, COACH_LOG_LEVEL, COACH_ENV .coach_cache/logs, INFO, dev JSON logs and the environment tag

Tests and quality

pytest -m "not live"        # offline, no network, no key needed
pytest -m live -s           # real Gemini calls (needs GOOGLE_API_KEY); prints cost and cache tokens
ruff check . && ruff format --check .

Editing a prompt: change src/ai_coach/prompts/*.md; tests/test_prompts.py checks the worked examples against the guardrails, so an example that teaches a rule violation fails the build. After changing schemas.py run python tools/export_schema.py.

Limits (be honest with users)

  • The coach cannot be more accurate than the metrics. Reference ranges are mostly unverified drafts, so notes say "typical range" and add a "ranges are drafts" caveat. Pitching has not been validated on real 240 fps footage.
  • No memory across sessions yet (no trend or "fixed" moments); the pipeline owns session history.
  • Never log or commit the API key. .env is git-ignored.