Spaces:
Running on T4
Running on T4
github-actions[bot] commited on
Commit ·
40fe6bf
1
Parent(s): 6f63794
Automated Deploy: e021f8fccd8fb582a739a0762fb16f53814cb62a
Browse files
AI-coach-agent/src/ai_coach/config.py
CHANGED
|
@@ -4,6 +4,7 @@ from __future__ import annotations
|
|
| 4 |
|
| 5 |
from functools import lru_cache
|
| 6 |
from pathlib import Path
|
|
|
|
| 7 |
|
| 8 |
from pydantic import BaseModel, Field, SecretStr
|
| 9 |
from pydantic_settings import BaseSettings, SettingsConfigDict
|
|
@@ -40,7 +41,9 @@ class Settings(BaseSettings):
|
|
| 40 |
timeout_s: float = 20.0
|
| 41 |
max_retries: int = 1 # transport retries inside the Google client
|
| 42 |
video_review_model: str = "gemini-3.8-flash"
|
| 43 |
-
video_review_timeout_s: float = Field(default=
|
|
|
|
|
|
|
| 44 |
video_review_max_frames: int = Field(default=72, ge=12, le=96)
|
| 45 |
video_review_max_reps: int = Field(default=6, ge=1, le=8)
|
| 46 |
thinking_budget: int | None = None # Gemini 2.5 style; sent only when set; verify model support live
|
|
|
|
| 4 |
|
| 5 |
from functools import lru_cache
|
| 6 |
from pathlib import Path
|
| 7 |
+
from typing import Literal
|
| 8 |
|
| 9 |
from pydantic import BaseModel, Field, SecretStr
|
| 10 |
from pydantic_settings import BaseSettings, SettingsConfigDict
|
|
|
|
| 41 |
timeout_s: float = 20.0
|
| 42 |
max_retries: int = 1 # transport retries inside the Google client
|
| 43 |
video_review_model: str = "gemini-3.8-flash"
|
| 44 |
+
video_review_timeout_s: float = Field(default=90, gt=0, le=120)
|
| 45 |
+
video_review_max_output_tokens: int = Field(default=8000, ge=1000, le=16384)
|
| 46 |
+
video_review_thinking_level: Literal["auto", "low", "medium", "high"] = "low"
|
| 47 |
video_review_max_frames: int = Field(default=72, ge=12, le=96)
|
| 48 |
video_review_max_reps: int = Field(default=6, ge=1, le=8)
|
| 49 |
thinking_budget: int | None = None # Gemini 2.5 style; sent only when set; verify model support live
|
AI-coach-agent/src/ai_coach/video_review.py
CHANGED
|
@@ -11,7 +11,7 @@ import time
|
|
| 11 |
import uuid
|
| 12 |
from typing import Literal
|
| 13 |
|
| 14 |
-
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
| 15 |
|
| 16 |
from .config import Settings
|
| 17 |
from .cost import UsageLedger, compute_cost
|
|
@@ -93,6 +93,13 @@ class VisualNote(BaseModel):
|
|
| 93 |
return self
|
| 94 |
|
| 95 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
def unavailable(reason: str) -> dict:
|
| 97 |
return {"status": "unavailable", "reason_code": reason, "source": "poc_video_review",
|
| 98 |
"message": FAILURE_MESSAGES.get(reason, FAILURE_MESSAGES["provider_failed"]),
|
|
@@ -210,13 +217,22 @@ def gemini_generate(settings: Settings, frames: list[dict], facts: dict):
|
|
| 210 |
retry_options=types.HttpRetryOptions(attempts=1))) as client:
|
| 211 |
response = client.models.generate_content(model=settings.video_review_model,
|
| 212 |
contents=contents, config=types.GenerateContentConfig(temperature=0,
|
| 213 |
-
max_output_tokens=
|
|
|
|
|
|
|
|
|
|
| 214 |
response_json_schema=visual_response_schema()))
|
| 215 |
usage = response.usage_metadata
|
| 216 |
counts = Usage(input_tokens=(usage.prompt_token_count or 0) if usage else 0,
|
| 217 |
output_tokens=((usage.candidates_token_count or 0) + (usage.thoughts_token_count or 0)) if usage else 0,
|
| 218 |
cached_tokens=(usage.cached_content_token_count or 0) if usage else 0,
|
| 219 |
reasoning_tokens=(usage.thoughts_token_count or 0) if usage else 0)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 220 |
return response.text, counts
|
| 221 |
|
| 222 |
|
|
@@ -271,11 +287,32 @@ def review_video(frames: list[dict], facts: dict, settings: Settings,
|
|
| 271 |
except Exception as error:
|
| 272 |
# Provider errors can include credentials and uploaded content. Public
|
| 273 |
# responses carry a fixed code, never provider text or a traceback.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 274 |
if outcome == "provider_failed":
|
| 275 |
result = provider_failure(error)
|
| 276 |
outcome = result["reason_code"]
|
| 277 |
return result
|
| 278 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 279 |
finally:
|
| 280 |
usage.cost_usd = compute_cost(settings.video_review_model, usage, settings.prices)
|
| 281 |
ledger.record_call(request_id=uuid.uuid4().hex[:12], model=settings.video_review_model,
|
|
|
|
| 11 |
import uuid
|
| 12 |
from typing import Literal
|
| 13 |
|
| 14 |
+
from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator
|
| 15 |
|
| 16 |
from .config import Settings
|
| 17 |
from .cost import UsageLedger, compute_cost
|
|
|
|
| 93 |
return self
|
| 94 |
|
| 95 |
|
| 96 |
+
class IncompleteVisualResponse(ValueError):
|
| 97 |
+
def __init__(self, reason, usage):
|
| 98 |
+
self.reason = reason
|
| 99 |
+
self.usage = usage
|
| 100 |
+
super().__init__("Google did not return a complete visual response")
|
| 101 |
+
|
| 102 |
+
|
| 103 |
def unavailable(reason: str) -> dict:
|
| 104 |
return {"status": "unavailable", "reason_code": reason, "source": "poc_video_review",
|
| 105 |
"message": FAILURE_MESSAGES.get(reason, FAILURE_MESSAGES["provider_failed"]),
|
|
|
|
| 217 |
retry_options=types.HttpRetryOptions(attempts=1))) as client:
|
| 218 |
response = client.models.generate_content(model=settings.video_review_model,
|
| 219 |
contents=contents, config=types.GenerateContentConfig(temperature=0,
|
| 220 |
+
max_output_tokens=settings.video_review_max_output_tokens,
|
| 221 |
+
thinking_config=(types.ThinkingConfig(thinking_level=settings.video_review_thinking_level)
|
| 222 |
+
if settings.video_review_thinking_level != "auto" else None),
|
| 223 |
+
response_mime_type="application/json",
|
| 224 |
response_json_schema=visual_response_schema()))
|
| 225 |
usage = response.usage_metadata
|
| 226 |
counts = Usage(input_tokens=(usage.prompt_token_count or 0) if usage else 0,
|
| 227 |
output_tokens=((usage.candidates_token_count or 0) + (usage.thoughts_token_count or 0)) if usage else 0,
|
| 228 |
cached_tokens=(usage.cached_content_token_count or 0) if usage else 0,
|
| 229 |
reasoning_tokens=(usage.thoughts_token_count or 0) if usage else 0)
|
| 230 |
+
candidate = response.candidates[0] if response.candidates else None
|
| 231 |
+
finish = candidate.finish_reason.value if candidate and candidate.finish_reason else None
|
| 232 |
+
if finish == "MAX_TOKENS":
|
| 233 |
+
raise IncompleteVisualResponse("output_truncated", counts)
|
| 234 |
+
if finish not in (None, "STOP") or not response.text:
|
| 235 |
+
raise IncompleteVisualResponse("no_complete_text", counts)
|
| 236 |
return response.text, counts
|
| 237 |
|
| 238 |
|
|
|
|
| 287 |
except Exception as error:
|
| 288 |
# Provider errors can include credentials and uploaded content. Public
|
| 289 |
# responses carry a fixed code, never provider text or a traceback.
|
| 290 |
+
if isinstance(error, IncompleteVisualResponse):
|
| 291 |
+
usage = error.usage
|
| 292 |
+
outcome = "invalid_visual_response"
|
| 293 |
+
return {**unavailable(outcome), "validation_reason": error.reason}
|
| 294 |
if outcome == "provider_failed":
|
| 295 |
result = provider_failure(error)
|
| 296 |
outcome = result["reason_code"]
|
| 297 |
return result
|
| 298 |
+
result = unavailable(outcome)
|
| 299 |
+
if isinstance(error, ValidationError):
|
| 300 |
+
# Error inputs and messages may contain model text or image data.
|
| 301 |
+
allowed = {"json_invalid", "missing", "string_too_long", "string_too_short",
|
| 302 |
+
"too_long", "too_short", "extra_forbidden", "literal_error",
|
| 303 |
+
"int_parsing", "list_type", "model_type", "value_error"}
|
| 304 |
+
result["validation_reasons"] = sorted({e["type"] for e in error.errors(include_input=False)
|
| 305 |
+
if e["type"] in allowed})
|
| 306 |
+
elif isinstance(error, ValueError):
|
| 307 |
+
checks = {"Evidence must be unique and chronological": "evidence_order",
|
| 308 |
+
"Evidence must refer to sampled frames from the named rep": "evidence_reference",
|
| 309 |
+
"Observed movement needs multiple frames": "insufficient_evidence",
|
| 310 |
+
"Visual feedback cannot invent measured or medical claims": "unsupported_claim",
|
| 311 |
+
"Contact claim without visible interaction": "unsupported_contact",
|
| 312 |
+
"Priority needs observed evidence and a matching library drill": "unsupported_priority",
|
| 313 |
+
"Priority cannot invent measured or medical claims": "unsupported_priority_claim"}
|
| 314 |
+
result["validation_reason"] = checks.get(str(error), "invalid_response")
|
| 315 |
+
return result
|
| 316 |
finally:
|
| 317 |
usage.cost_usd = compute_cost(settings.video_review_model, usage, settings.prices)
|
| 318 |
ledger.record_call(request_id=uuid.uuid4().hex[:12], model=settings.video_review_model,
|
docs/SWING_COACH_PRODUCT.md
CHANGED
|
@@ -23,7 +23,11 @@ Optional settings:
|
|
| 23 |
- `COACH_VIDEO_REVIEW_MODEL`: default `gemini-3.8-flash`.
|
| 24 |
- `COACH_DAILY_BUDGET_USD`: default `1`; calls stop once recorded daily spend
|
| 25 |
reaches this amount. This is a spend stop, not a hard per-call billing cap.
|
| 26 |
-
- `COACH_VIDEO_REVIEW_TIMEOUT_S`: default `
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
- `COACH_VIDEO_REVIEW_MAX_FRAMES`: default `72`, maximum `96`.
|
| 28 |
- `COACH_VIDEO_REVIEW_MAX_REPS`: default `6`, maximum `8`.
|
| 29 |
|
|
@@ -143,6 +147,10 @@ Schema constraints. Unsupported default and string-length keywords are removed
|
|
| 143 |
from the provider request; the full Pydantic length, evidence and content checks
|
| 144 |
still run locally before feedback is accepted. This avoids the rejected legacy
|
| 145 |
OpenAPI `response_schema` request format.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
|
| 147 |
Space results need persistent server storage to survive rebuilds. On a Space
|
| 148 |
using temporary storage, save the product JSON and any needed evidence images
|
|
|
|
| 23 |
- `COACH_VIDEO_REVIEW_MODEL`: default `gemini-3.8-flash`.
|
| 24 |
- `COACH_DAILY_BUDGET_USD`: default `1`; calls stop once recorded daily spend
|
| 25 |
reaches this amount. This is a spend stop, not a hard per-call billing cap.
|
| 26 |
+
- `COACH_VIDEO_REVIEW_TIMEOUT_S`: default `90`, no transport retries.
|
| 27 |
+
- `COACH_VIDEO_REVIEW_MAX_OUTPUT_TOKENS`: default `8000`, maximum `16384`;
|
| 28 |
+
includes model reasoning as well as returned feedback.
|
| 29 |
+
- `COACH_VIDEO_REVIEW_THINKING_LEVEL`: default `low` for Gemini 3.8 Flash.
|
| 30 |
+
Use `auto` to omit this setting when switching to a model without level support.
|
| 31 |
- `COACH_VIDEO_REVIEW_MAX_FRAMES`: default `72`, maximum `96`.
|
| 32 |
- `COACH_VIDEO_REVIEW_MAX_REPS`: default `6`, maximum `8`.
|
| 33 |
|
|
|
|
| 147 |
from the provider request; the full Pydantic length, evidence and content checks
|
| 148 |
still run locally before feedback is accepted. This avoids the rejected legacy
|
| 149 |
OpenAPI `response_schema` request format.
|
| 150 |
+
Incomplete model responses are rejected and reported as `output_truncated` or
|
| 151 |
+
`no_complete_text`. Other validation failures expose only fixed reason codes,
|
| 152 |
+
never rejected model text. Billed reasoning tokens are counted even when the
|
| 153 |
+
response is incomplete.
|
| 154 |
|
| 155 |
Space results need persistent server storage to survive rebuilds. On a Space
|
| 156 |
using temporary storage, save the product JSON and any needed evidence images
|
tests/test_product.py
CHANGED
|
@@ -186,7 +186,7 @@ def test_actual_sdk_request_uses_images_schema_timeouts_and_billed_usage(tmp_pat
|
|
| 186 |
candidates_token_count=20,thoughts_token_count=5,cached_content_token_count=10))
|
| 187 |
class Client:
|
| 188 |
def __init__(self,**kwargs):
|
| 189 |
-
assert kwargs['http_options'].timeout==
|
| 190 |
assert kwargs['http_options'].retry_options.attempts==1
|
| 191 |
self.models=Models()
|
| 192 |
def __enter__(self):return self
|
|
@@ -197,6 +197,8 @@ def test_actual_sdk_request_uses_images_schema_timeouts_and_billed_usage(tmp_pat
|
|
| 197 |
assert json.loads(raw)['features'][0]['key']=='load_timing'
|
| 198 |
assert usage.input_tokens==50 and usage.output_tokens==25 and usage.cached_tokens==10
|
| 199 |
assert calls[0]['config'].response_mime_type=='application/json'
|
|
|
|
|
|
|
| 200 |
assert calls[0]['config'].response_schema is None
|
| 201 |
assert calls[0]['config'].response_json_schema['properties']['features']['minItems']==3
|
| 202 |
assert len([p for p in calls[0]['contents'] if p.inline_data])==3
|
|
@@ -373,7 +375,8 @@ def test_retry_storage_failure_keeps_the_previous_product(tmp_path,monkeypatch):
|
|
| 373 |
assert client.get(url+'/product',headers=AUTH).json()==product
|
| 374 |
|
| 375 |
|
| 376 |
-
|
|
|
|
| 377 |
from google import genai
|
| 378 |
from google.genai import types
|
| 379 |
from pydantic import SecretStr
|
|
@@ -389,11 +392,17 @@ def test_real_google_sdk_serializes_our_schema_and_decodes_response(tmp_path,mon
|
|
| 389 |
client._api_client.request=transport
|
| 390 |
return client
|
| 391 |
monkeypatch.setattr(genai,'Client',make_client)
|
| 392 |
-
configured=coach_settings(tmp_path).model_copy(update={'google_api_key':SecretStr('test-not-a-key')
|
|
|
|
| 393 |
raw,usage=gemini_generate(configured,frames(),{})
|
| 394 |
assert json.loads(raw)['features'][0]['key']=='load_timing'
|
| 395 |
assert usage.input_tokens==50 and usage.output_tokens==20
|
| 396 |
config=requests[0]['generationConfig']
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 397 |
assert 'responseSchema' not in config
|
| 398 |
schema=config['responseJsonSchema']
|
| 399 |
assert schema['properties']['features']['minItems']==3
|
|
@@ -412,3 +421,41 @@ def test_provider_schema_subset_keeps_local_length_and_evidence_validation(tmp_p
|
|
| 412 |
too_long['features'][0]['observation']='x'*551
|
| 413 |
result=review_video(frames(),{},coach_settings(tmp_path),generator=lambda *a:(json.dumps(too_long),Usage()))
|
| 414 |
assert result['reason_code']=='invalid_visual_response'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 186 |
candidates_token_count=20,thoughts_token_count=5,cached_content_token_count=10))
|
| 187 |
class Client:
|
| 188 |
def __init__(self,**kwargs):
|
| 189 |
+
assert kwargs['http_options'].timeout==90000
|
| 190 |
assert kwargs['http_options'].retry_options.attempts==1
|
| 191 |
self.models=Models()
|
| 192 |
def __enter__(self):return self
|
|
|
|
| 197 |
assert json.loads(raw)['features'][0]['key']=='load_timing'
|
| 198 |
assert usage.input_tokens==50 and usage.output_tokens==25 and usage.cached_tokens==10
|
| 199 |
assert calls[0]['config'].response_mime_type=='application/json'
|
| 200 |
+
assert calls[0]['config'].max_output_tokens==8000
|
| 201 |
+
assert calls[0]['config'].thinking_config.thinking_level.value=='LOW'
|
| 202 |
assert calls[0]['config'].response_schema is None
|
| 203 |
assert calls[0]['config'].response_json_schema['properties']['features']['minItems']==3
|
| 204 |
assert len([p for p in calls[0]['contents'] if p.inline_data])==3
|
|
|
|
| 375 |
assert client.get(url+'/product',headers=AUTH).json()==product
|
| 376 |
|
| 377 |
|
| 378 |
+
@pytest.mark.parametrize('thinking_level',['low','auto'])
|
| 379 |
+
def test_real_google_sdk_serializes_our_schema_and_decodes_response(tmp_path,monkeypatch,thinking_level):
|
| 380 |
from google import genai
|
| 381 |
from google.genai import types
|
| 382 |
from pydantic import SecretStr
|
|
|
|
| 392 |
client._api_client.request=transport
|
| 393 |
return client
|
| 394 |
monkeypatch.setattr(genai,'Client',make_client)
|
| 395 |
+
configured=coach_settings(tmp_path).model_copy(update={'google_api_key':SecretStr('test-not-a-key'),
|
| 396 |
+
'video_review_thinking_level':thinking_level})
|
| 397 |
raw,usage=gemini_generate(configured,frames(),{})
|
| 398 |
assert json.loads(raw)['features'][0]['key']=='load_timing'
|
| 399 |
assert usage.input_tokens==50 and usage.output_tokens==20
|
| 400 |
config=requests[0]['generationConfig']
|
| 401 |
+
assert config['maxOutputTokens']==8000
|
| 402 |
+
if thinking_level=='auto':
|
| 403 |
+
assert 'thinkingConfig' not in config
|
| 404 |
+
else:
|
| 405 |
+
assert config['thinkingConfig']['thinking_level']=='LOW'
|
| 406 |
assert 'responseSchema' not in config
|
| 407 |
schema=config['responseJsonSchema']
|
| 408 |
assert schema['properties']['features']['minItems']==3
|
|
|
|
| 421 |
too_long['features'][0]['observation']='x'*551
|
| 422 |
result=review_video(frames(),{},coach_settings(tmp_path),generator=lambda *a:(json.dumps(too_long),Usage()))
|
| 423 |
assert result['reason_code']=='invalid_visual_response'
|
| 424 |
+
assert result['validation_reasons']==['string_too_long']
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
def test_truncated_google_response_reports_safe_reason_and_keeps_billed_usage(tmp_path,monkeypatch):
|
| 428 |
+
from google import genai
|
| 429 |
+
from google.genai import types
|
| 430 |
+
from pydantic import SecretStr
|
| 431 |
+
from ai_coach.cost import UsageLedger
|
| 432 |
+
from ai_coach.video_review import review_video
|
| 433 |
+
configured=coach_settings(tmp_path).model_copy(update={'google_api_key':SecretStr('test-not-a-key')})
|
| 434 |
+
class Client:
|
| 435 |
+
def __init__(self,**kw):self.models=self
|
| 436 |
+
def __enter__(self):return self
|
| 437 |
+
def __exit__(self,*a):pass
|
| 438 |
+
def generate_content(self,**kw):
|
| 439 |
+
return types.GenerateContentResponse(candidates=[types.Candidate(finish_reason='MAX_TOKENS',
|
| 440 |
+
content=types.Content(parts=[types.Part.from_text(text='private model content')]))],
|
| 441 |
+
usage_metadata=types.GenerateContentResponseUsageMetadata(prompt_token_count=100,
|
| 442 |
+
thoughts_token_count=2500))
|
| 443 |
+
monkeypatch.setattr(genai,'Client',Client)
|
| 444 |
+
ledger=UsageLedger(configured.resolved_ledger_path,1)
|
| 445 |
+
result=review_video(frames(),{},configured,ledger=ledger)
|
| 446 |
+
assert result['validation_reason']=='output_truncated'
|
| 447 |
+
assert 'private model content' not in json.dumps(result)
|
| 448 |
+
assert ledger._query('SELECT input_tokens, output_tokens, reasoning_tokens, cost_usd FROM calls')[0][:3]==(100,2500,2500)
|
| 449 |
+
assert ledger._query('SELECT cost_usd FROM calls')[0][0]>0
|
| 450 |
+
|
| 451 |
+
|
| 452 |
+
@pytest.mark.parametrize('alter,reason',[
|
| 453 |
+
(lambda n:n['features'][0].update(evidence_frame_ids=[2,1]),'evidence_order'),
|
| 454 |
+
(lambda n:n['features'][0].update(evidence_frame_ids=[1,999]),'evidence_reference'),
|
| 455 |
+
(lambda n:n['features'][0].update(observation='Your swing took 100 ms.'),'unsupported_claim')])
|
| 456 |
+
def test_visual_validation_reports_allowlisted_reason_without_model_text(tmp_path,alter,reason):
|
| 457 |
+
from ai_coach.video_review import review_video
|
| 458 |
+
bad=note();alter(bad)
|
| 459 |
+
result=review_video(frames(),{},coach_settings(tmp_path),generator=lambda *a:(json.dumps(bad),Usage()))
|
| 460 |
+
assert result['validation_reason']==reason
|
| 461 |
+
assert bad['features'][0]['observation'] not in json.dumps(result)
|