# Frontend integration guide **For:** the mobile app / backend developer who shows the coaching result to the player. **Building the screen?** See [FRONTEND_UI_GUIDE.md](FRONTEND_UI_GUIDE.md) (what to show for each field and state, with sample responses in `examples/responses/`). **Related:** [DEPLOYMENT.md](DEPLOYMENT.md) (running the service), [AGENT_INPUT_SPEC.md](AGENT_INPUT_SPEC.md) (the measurements the ML pipeline produces). ## 1. The picture ``` phone video -> ML pipeline (pose + measurements) -> session JSON -> [your backend] -> AI Coach API -> coaching response (v2.0) -> your app screen ``` - The **ML pipeline** produces the session JSON (measurements only). - **Your backend** forwards it to the AI Coach API and returns the response to the app. - **The app** only renders the response. It never decides what is wrong and never calculates the score; the response already has both. ### Calling from the mobile app CORS does not apply to native iOS/Android apps, so the app can call the API directly. The catch is the key: > **Anything shipped inside an app (a hard-coded key, a config file, an `.env`) can be extracted by anyone who downloads the app.** > With a shared `X-API-Key` in the app, a stranger could call the API as often as they like. The daily budget caps the damage (each container stops calling Gemini at `COACH_DAILY_BUDGET_USD`, default $1, and then serves free rule-based notes), but real players would get worse notes until the next day. | Option | How | Use when | |---|---|---| | **A. Through your backend (recommended)** | App sends the session (or just a session id) to your backend, which holds the key and forwards the call. | You have a backend that already authenticates users. Best: the ML pipeline's backend calls the coach right after it computes the measurements and returns the finished note to the app, so the app never handles the session JSON. | | **B. Direct from the app** | App calls `/v1/coach` with a key it fetches **after the user logs in**, never one baked into the build. Put the API behind a gateway that does per-user auth and rate limiting (for example 20 requests per user per hour). | Early pilot with few trusted testers. A key in the build is acceptable only for a closed pilot, with a low `COACH_DAILY_BUDGET_USD` and a plan to rotate the key. | Either way: use HTTPS only, set the request timeout to 30 s, and rotate `COACH_API_KEY` if it ever leaks (change the env var and redeploy). ## 2. The one endpoint you need ``` POST {BASE_URL}/v1/coach?level=hs_varsity X-API-Key: Content-Type: application/json ``` | Part | Value | |---|---| | `level` (query, optional) | `hs_jv`, `hs_varsity` or `college`. Overrides `level` inside the JSON. If neither is given the API assumes `hs_varsity` (the note then says the level was assumed, see `caveats`). | | Body | One session JSON (section 3), with optional `timing`. Max **2 MB**. | | Typical latency | 1.5 to 3 s when Gemini writes the note, a few ms when it is cached or rule-based. Set your client timeout to **30 s**. | | Cost | About $0.0013 per new note; $0 for repeats and rule-based notes. | Other endpoints: `GET /v1/usage?days=7` (cost and cache report, needs the key), `GET /healthz`, `GET /readyz` (no key; `readyz` returns `{"status":"ready","llm":true,"model":"..."}`). In non-prod environments the interactive docs are at `/docs`. ## 3. What the API accepts (request body) A session of **measurements only**, plus optional **timing**. Full definitions: [AGENT_INPUT_SPEC.md](AGENT_INPUT_SPEC.md). Minimal valid shape: ```json { "schema_version": "2.0", "session_id": "sess_42", "discipline": "hitting", "level": "hs_varsity", "view": "face_on", "fps": 240.0, "capture": { "ok": true, "reasons": [] }, "reps": [ { "rep": 1, "events_ms": { "foot_plant": 1000, "contact": 1221 }, "metrics": [ { "key": "stride_pct_height", "value": 61.7, "unit": "%", "confidence": "high" }, { "key": "com_drift_pct_height", "value": -12.0, "unit": "%", "confidence": "medium" }, { "key": "load_tempo_s", "value": null, "unit": "s", "confidence": "est", "note": "not computed: event 'load_start' not found" } ] } ] } ``` | Field | Required | Notes | |---|---|---| | `discipline` | yes | `"hitting"` or `"pitching"` | | `reps[]` | yes | Every rep separately, at least 3 when possible. Each has `metrics[]` with `key`, `value` (number or `null`), `unit`, `confidence` (`high`, `medium` or `est`) and an optional `note`. | | `fps` | strongly advised | The **real capture** frame rate (240 for slow motion). Timing metrics are dropped below 60 fps. | | `capture` | advised | `{ "ok": bool, "reasons": [...] }`. If `ok` is `false` the response only asks the player to record again, and the score is `null`. | | `level` | optional | `hs_jv` / `hs_varsity` / `college` (or use the query parameter). | | `session_id` | optional | Your own id, up to 64 characters of `A-Z a-z 0-9 _ . : -`. It is echoed back in the response so you can match it. Anything else is dropped. Never send names. | | `arm_care` | optional, pitching only | Pitch-count facts from **your app**: `{ "known": true, "pitch_count_today": 40, "daily_max": 95, "next_eligible_date": "2026-10-13", "alerts": [] }`. They are repeated exactly in the response's `arm_care`, never advised on. | | `timing` | optional, hitting only | The engine's load-and-timing object (below). Ignored for pitching. | ### 3.1 The `timing` object (contract 3.1, hitting only) The engine measures **when** movements happen. The API turns it into the response's `timing` section. A bad `timing` object is a `422` and costs nothing. ```json "timing": { "schema_version": "3.1", "discipline": "hitting", "capture": { "capture_fps": 240.0, "time_source": "original_pts" }, "reps": [ { "rep": 1, "outcome": "unknown", "stepped": true, "context": { "practice_type": "tee" }, "frame_interval_ms": { "min": 4.1, "median": 4.17, "max": 4.3 }, "metrics": [ { "key": "load_to_swing_ms", "value": 300, "unit": "ms", "status": "estimated", "confidence": "est" }, { "key": "foot_down_to_swing_ms", "value": 50, "unit": "ms", "status": "estimated", "confidence": "est", "order_resolved": true }, { "key": "swing_duration_ms", "value": null, "unit": "ms", "status": "unclear", "reason_codes": ["actual_end_unavailable"] }, { "key": "early_late_shift_ms", "value": null, "unit": "ms", "status": "not_applicable" } ] } ] } ``` | Field | Notes | |---|---| | `schema_version` | `"3.0"` or `"3.1"`. Anything else is a 422. | | `capture.time_source` | `original_pts`, `slowmo_rescaled`, `explicit_capture_times` or `unknown`. With `unknown` no timing number is shown (playback time must never be turned into milliseconds). | | `reps[].outcome` | `hit`, `miss` or `unknown`. | | `reps[].context.practice_type` | `tee`, `soft_toss`, `machine`, `live`, `dry_swing` or `unknown`. Swings are only compared with each other within the same known practice type. | | `metrics[].status` | `estimated`, `not_applicable` or `unclear`. A `null` value is never shown as zero. | | `metrics[].reason_codes` | Machine-readable reasons (for example `no_step`, `outcome_unknown`). The player sees fixed sentences for the known codes; unknown codes are ignored. Free-text notes are never shown. | | `metrics[].judgment_eligible` | Default `false`. Today nothing is eligible, so the timing section only describes. | | `swing_duration_ms` | Only shown when `end_event` is `contact` or `closest_approach` **and** `end_event_source` is set. An arm-extension proxy is never an endpoint. | | `foot_down_to_swing_ms` | The sign (before or after) is only stated when `order_resolved` is `true`. | **Timing on its own.** You may also post the engine's timing payload (`schema_version` 3.0 or 3.1) as the whole body, exactly as the engine returns it. The response then has the same shape with only `timing` filled: `score.value` is `null`, `focus`, `strengths` and `drill` are empty, `summary` repeats the timing summary and `meta.fallback_reason` is `"timing_only"`. Contract 3.0 says `time_basis: "capture"` instead of `capture.time_source`; both are accepted (`capture` means real recording time, `playback` means no numbers are shown). **Do not send:** faults, a priority fix, drills, explanations, ranges, zones, video, frames, keypoints, names or ids. These are ignored (the agent decides them itself). Unknown metric keys are ignored; values outside physically possible bounds are treated as missing. Check a file before sending: `python -m ai_coach.validate session.json` (it also checks `timing`). ## 4. What the API returns (200): `response_version` "2.0" This **replaces** the earlier `note` shape. There is no `note`, `usage`, `chosen_problem` or similar field any more. ```json { "response_version": "2.0", "request_id": "73b87e482de5", "session_id": "sess_42", "discipline": "hitting", "level": "college", "level_assumed": false, "score": { "name": "Mechanics score", "meaning": "How close your measured mechanics are to the typical range for your level. Typical is not the same as ideal, and this is not a rating of how good a player you are.", "value": 77, "band": "Mostly close to typical", "confidence": "medium", "basis": "2 of 9 measurements, 6 swings", "in_range": 0, "checked": 2, "breakdown": [ { "metric_key": "stride_pct_height", "label": "Stride length", "score": 84, "weight": 0.588, "zone": "outside_typical_range" }, { "metric_key": "com_drift_pct_height", "label": "Body drift past front foot", "score": 67, "weight": 0.412, "zone": "outside_typical_range" } ], "reason_code": null, "reason": null }, "summary": "Here is the one thing to work on in your swing.", "strengths": [], "focus": [ { "problem_key": "lunging", "evidence": [ "com_drift_pct_height" ], "text": "Your body slides forward past your front foot. Your weight gets ahead of your hands, and you lose power from the ground. This showed up in 100% of your reps." }, { "problem_key": "over_stride", "evidence": [ "stride_pct_height" ], "text": "Your front foot lands too far out." } ], "drill": { "name": "Balance Hold Tee", "how": "Do 3x8. Turn, don't slide.", "cue": "Stay behind your front knee. Turn, don't slide." }, "timing": { "summary": "Timing: Preparation to swing and Front foot down to swing were estimated. Swing duration and Early or late adjustment are unavailable.", "observations": [ { "metric_key": "load_to_swing_ms", "label": "Preparation to swing", "value_ms": 300, "swings": 1, "range_ms": null, "status": "estimated", "text": "Your preparation to the start of the forward swing took about 300 ms." }, { "metric_key": "foot_down_to_swing_ms", "label": "Front foot down to swing", "value_ms": 50, "swings": 1, "range_ms": null, "status": "estimated", "text": "About 50 ms passed between your front foot first touching down and your swing starting. The video cannot show which came first." } ], "unavailable": [ { "metric_key": "swing_duration_ms", "label": "Swing duration", "reason_codes": [], "text": "This could not be measured reliably from this video." }, { "metric_key": "early_late_shift_ms", "label": "Early or late adjustment", "reason_codes": [], "text": "This could not be measured reliably from this video." } ], "data_quality": [ "These timing numbers are estimates. On their own they cannot show a timing fault.", "Whether the bat met the ball was not established, so hits and misses were not compared.", "Only one swing was timed, so there is nothing to compare it with." ], "consistency": null }, "data_quality": [ "Some numbers are only estimates from one camera, so we are not judging them." ], "arm_care": null, "meta": { "source": "rules", "model": null, "prompt_version": "coach-v1-f0891b43", "cache_hit": false, "fallback_reason": "llm_disabled", "latency_ms": 4 } } ``` ### 4.1 Fields the app shows | Field | Type | How to render | |---|---|---| | `score` | object | The mechanics score (4.2). Always present; `value` can be `null`. | | `summary` | string | Big title. Always present. | | `strengths` | 0 to 3 × `{metric_key, text}` | "What looks good". Show `text`. | | `focus` | 0 to 2 × `{problem_key, evidence[], text}` | "What to work on". **The first item is the priority fix.** `text` is player-ready. | | `drill` | `{name, how, cue}` or `null` | "Try this drill", with the priority fix's cue shown prominently. `null` when there is nothing to fix. | | `timing` | object or `null` | The load-and-timing section (4.3). `null` when no `timing` was sent. | | `arm_care` | object or `null` | Pitching only. Show `lines` as given, they repeat your own app's facts. | | `data_quality` | 0 to 3 × string | "Keep in mind" notes (video quality, draft ranges, "record again"). **Always show them.** | All text is plain, short and player-ready. Render it as given; do not rewrite or translate numbers. Every block can be empty or `null`; design each so it disappears cleanly. ### 4.2 The score ``` "score": { "name": "Mechanics score", "meaning": "...", "value": 77, "band": "Mostly close to typical", "confidence": "medium", "basis": "2 of 9 measurements, 6 swings", "in_range": 0, "checked": 2, "breakdown": [ { "metric_key": "...", "label": "...", "score": 84, "weight": 0.588, "zone": "..." } ], "reason_code": null, "reason": null } ``` - `value` is 0 to 100, or `null` when there is not enough to score (`reason_code`: `capture_not_ok` or `not_enough_measurements`, with a plain `reason`). **Show `reason` instead of a number; never show 0.** - It is calculated by code from the measurements, not by the AI. The same swings always give the same number. - It means how close the measured mechanics are to the typical range for the player's level. **It is not a rating of the player, and typical is not the same as ideal.** Show `name` as the label and keep `meaning` reachable (an info icon). - `confidence` (`high`, `medium`, `low`) says how much to trust it. Low is common for high school levels, whose ranges rest on few athletes. Consider showing it as a small tag. - `basis` says what it rests on. Today hitting has only two measurements with calibrated ranges (stride and body drift), so a hitting score rests on at most two. Show `basis` near the number. - `breakdown` is optional detail ("what makes up the score"). Weights add up to 1. - Only judged measurements count. Estimates, reference-only measurements and all timing numbers are left out for now. ### 4.3 The `timing` section | Field | Meaning | |---|---| | `summary` | One sentence: which timings were estimated and which are unavailable. | | `observations[]` | `{metric_key, label, value_ms, swings, range_ms, status: "estimated", text}`. `text` is player-ready; `value_ms` is for charts and is rounded to 10 ms. | | `unavailable[]` | `{metric_key, label, reason_codes[], text}`: what could not be measured and why, in plain words. | | `data_quality[]` | What the numbers cannot show (frame length of the video, hits and misses not compared, estimates only). Show them under the section. | | `consistency` | `{practice_type, swings, notes[]}` or `null`. Only with at least 5 swings of the same known practice type. | The section is descriptive only. It never says a player was early, late or rushed, and it says so in `data_quality`. Do not build "good or bad" colouring on `value_ms`. ### 4.4 `meta`: not for the player | Field | Meaning | Use | |---|---|---| | `source` | `"llm"` (the model wrote the text) or `"rules"` (fixed-rule text) | Both are safe to show. | | `fallback_reason` | Why `source` is `rules`: `nothing_to_judge`, `llm_disabled`, `daily_budget_exceeded`, `cached_failure:...`, or a model failure | Logging only. | | `cache_hit`, `model`, `prompt_version`, `latency_ms` | Debugging | Internal dashboards only. | | `request_id` (top level) | Ties the response to server logs and LangSmith | **Log it and attach it to support tickets.** | The score, `timing` and `arm_care` are the same whether `source` is `llm` or `rules`. ### 4.5 Cases the UI must handle 1. **Record again.** When the capture failed: `score.value` is `null`, `focus` and `strengths` are empty, there is no `drill`, and `data_quality[0]` asks the player to record again. Show it as its own screen. 2. **Nothing to work on.** `focus` is empty but `strengths` is not: show a positive result. 3. **Score is `null`** with a good video: fewer than two measurements could be judged. Show `score.reason` and still show the rest. 4. **Rule-based text** (`meta.source: "rules"`): shorter and more generic, but valid. 5. **Draft ranges.** `data_quality` may say the typical ranges for the level are drafts or rough. Keep it visible; it is deliberate honesty. ## 5. Errors | Status | Body | Meaning | What to do | |---|---|---|---| | 401 | `{"detail": "missing or invalid X-API-Key"}` | Key missing or wrong | Fix your server config. Do not retry. | | 413 | `{"detail": "session too large"}` | Body over 2 MB | Send measurements only; never keypoints or video. | | 422 | `{"detail": "..."}` | Bad JSON, bad measurements or bad `timing`. The detail says what to fix (for example `timing.schema_version must be one of [...]`) | A bug on the sending side. Fix it; do not retry. | | 500 | `{"detail": "internal error"}` | Unexpected server error | Retry once after 1 s, then show "try again later". | Model, network and budget problems are **not** errors: you still get a 200 with rule-based text. Timeouts or connection errors on your side: retry once. Repeating a request is safe (identical sessions are cached and cost nothing). ## 6. Example calls **curl** ```bash curl -s -X POST "https://coach.example.com/v1/coach?level=hs_varsity" \ -H "X-API-Key: $COACH_API_KEY" -H "Content-Type: application/json" \ -d @session.json ``` **Node / TypeScript (your backend; the same call works from React Native with the key fetched after login)** ```ts export interface CoachResponse { response_version: "2.0"; request_id: string; session_id: string | null; discipline: "hitting" | "pitching"; level: string | null; score: { name: string; meaning: string; value: number | null; band: string | null; confidence: "high" | "medium" | "low" | null; basis: string | null; in_range: number; checked: number; reason: string | null; breakdown: { metric_key: string; label: string; score: number; weight: number }[]; }; summary: string; strengths: { metric_key: string; text: string }[]; focus: { problem_key: string; evidence: string[]; text: string }[]; drill: { name: string; how: string; cue: string | null } | null; timing: { summary: string; observations: { metric_key: string; label: string; value_ms: number; swings: number; text: string }[]; unavailable: { metric_key: string; label: string; reason_codes: string[]; text: string }[]; data_quality: string[]; consistency: { practice_type: string; swings: number; notes: string[] } | null; } | null; arm_care: { lines: string[] } | null; data_quality: string[]; meta: { source: "llm" | "rules"; fallback_reason: string | null }; } export async function getCoach(session: unknown, level?: string): Promise { const url = new URL("/v1/coach", process.env.COACH_BASE_URL); if (level) url.searchParams.set("level", level); const res = await fetch(url, { method: "POST", headers: { "X-API-Key": process.env.COACH_API_KEY!, "Content-Type": "application/json" }, body: JSON.stringify(session), signal: AbortSignal.timeout(30_000), }); if (!res.ok) throw new Error(`coach ${res.status}: ${(await res.json()).detail}`); return res.json(); } ``` **React rendering sketch** ```tsx function CoachView({ r }: { r: CoachResponse }) { return (

{r.score.value ?? "No score"}{r.score.value !== null && / 100 ({r.score.confidence})}

{r.score.value === null &&

{r.score.reason}

}

{r.summary}

{r.strengths.length > 0 && (<>

What looks good

    {r.strengths.map(i =>
  • {i.text}
  • )}
)} {r.focus.length > 0 && (<>

What to work on

    {r.focus.map(i =>
  1. {i.text}
  2. )}
)} {r.drill &&

{r.drill.name}: {r.drill.how} {r.drill.cue && {r.drill.cue}}

} {r.timing && (<>

Timing

{r.timing.summary}

    {r.timing.observations.map(o =>
  • {o.text}
  • )}
{r.timing.data_quality.join(" ")})} {r.arm_care &&
    {r.arm_care.lines.map(l =>
  • {l}
  • )}
} {r.data_quality.length > 0 && (<>

Keep in mind

    {r.data_quality.map(c =>
  • {c}
  • )}
)}
); } ``` ## 7. Integration checklist - [ ] Decide option A or B in section 1. For A, only the backend holds `COACH_API_KEY`; for B, the key is never in the app build and the API sits behind per-user login and a rate limit. - [ ] Client timeout 30 s; one retry on timeout or 500. - [ ] Store `request_id` with every result shown to a player. - [ ] Show `score.reason` instead of a number when `score.value` is `null`; never show 0. - [ ] Show the score with its `name`, `basis` and `confidence`, and keep `meaning` one tap away. - [ ] Render every `data_quality` entry (response and timing), and the "record again" case as its own screen. - [ ] Every block can be missing without breaking the layout. - [ ] Pitching: send `arm_care` from the app's own pitch-count data (ISO dates). - [ ] Send `timing` (3.1) for hitting when the engine has it, with `capture.time_source` and `context.practice_type` filled in. - [ ] Do not build logic on `meta.source` or `problem_key` values beyond logging and analytics. - [ ] Run `python -m ai_coach.validate` on a sample from the real pipeline before go-live.