Spaces:
Running on T4
Running on T4
github-actions[bot] commited on
Commit ·
b6e922f
1
Parent(s): df8b40e
Automated Deploy: 0c43ed4283ac6d60f1eeb0ec8b48492237da6dd4
Browse files
AI-coach-agent/src/ai_coach/group_review.py
CHANGED
|
@@ -108,6 +108,22 @@ class RatingBatch(Strict):
|
|
| 108 |
groups: list[Rating] = Field(min_length=1, max_length=4)
|
| 109 |
|
| 110 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
def available_facts(groups):
|
| 112 |
facts=[]; evidence={}
|
| 113 |
for group in sorted(groups,key=lambda g:g.key):
|
|
@@ -180,7 +196,7 @@ def review_groups(service,groups):
|
|
| 180 |
settings=service.settings;canonical=json.dumps(facts,sort_keys=True,separators=(',',':'))
|
| 181 |
digest=hashlib.sha256((VERSION+PROMPT+settings.video_review_model+canonical).encode()).hexdigest()
|
| 182 |
folder=settings.cache_path.parent/'sam-group-reviews';folder.mkdir(parents=True,exist_ok=True)
|
| 183 |
-
path=folder/(digest+'.json');reason='coach_provider_failed';request_id=uuid.uuid4().hex[:12]
|
| 184 |
def generate(attempt,feedback):
|
| 185 |
usage=Usage();started=time.monotonic()
|
| 186 |
try:
|
|
@@ -190,7 +206,7 @@ def review_groups(service,groups):
|
|
| 190 |
response=client.models.generate_content(model=settings.video_review_model,
|
| 191 |
contents=PROMPT+'\n'+canonical+feedback,config=types.GenerateContentConfig(temperature=0,
|
| 192 |
max_output_tokens=settings.video_review_max_output_tokens,
|
| 193 |
-
response_mime_type='application/json',response_json_schema=
|
| 194 |
thinking_config=types.ThinkingConfig(thinking_level='low')))
|
| 195 |
u=response.usage_metadata
|
| 196 |
usage=Usage(input_tokens=(u.prompt_token_count or 0) if u else 0,
|
|
@@ -228,9 +244,15 @@ def review_groups(service,groups):
|
|
| 228 |
group.score=reviews[group.key]['score'];group.coaching=reviews[group.key]['coaching']
|
| 229 |
else:group.score.reason_code='no_available_measurements'
|
| 230 |
temporary=path.with_suffix('.tmp');temporary.write_text(raw);temporary.replace(path)
|
| 231 |
-
except Exception:
|
| 232 |
# Keep the measurements, and never invent a default score on failure.
|
| 233 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 234 |
finally:
|
| 235 |
for group in groups:
|
| 236 |
-
if group.score.status=='pending' and group.score.reason_code=='review_pending':
|
|
|
|
|
|
| 108 |
groups: list[Rating] = Field(min_length=1, max_length=4)
|
| 109 |
|
| 110 |
|
| 111 |
+
def provider_schema():
|
| 112 |
+
"""Inline structural schema matching the deployed measurement-review adapter.
|
| 113 |
+
|
| 114 |
+
Keep Pydantic reference/constraint metadata in our local validator; the wire
|
| 115 |
+
schema uses only the provider's basic object/array/string/integer vocabulary.
|
| 116 |
+
"""
|
| 117 |
+
def obj(properties):return {'type':'object','properties':properties,'required':list(properties),'additionalProperties':False}
|
| 118 |
+
def array(items):return {'type':'array','items':items}
|
| 119 |
+
string={'type':'string'}
|
| 120 |
+
point=obj({'text':string,'evidence_ids':array(string)})
|
| 121 |
+
aspect=obj({'key':string,'grade':{'type':'integer'},'explanation':string,'evidence_ids':array(string)})
|
| 122 |
+
rating=obj({'key':string,'aspects':array(aspect),'summary':string,
|
| 123 |
+
'what_went_well':array(point),'what_needs_work':array(point),'next_step':point})
|
| 124 |
+
return obj({'groups':array(rating)})
|
| 125 |
+
|
| 126 |
+
|
| 127 |
def available_facts(groups):
|
| 128 |
facts=[]; evidence={}
|
| 129 |
for group in sorted(groups,key=lambda g:g.key):
|
|
|
|
| 196 |
settings=service.settings;canonical=json.dumps(facts,sort_keys=True,separators=(',',':'))
|
| 197 |
digest=hashlib.sha256((VERSION+PROMPT+settings.video_review_model+canonical).encode()).hexdigest()
|
| 198 |
folder=settings.cache_path.parent/'sam-group-reviews';folder.mkdir(parents=True,exist_ok=True)
|
| 199 |
+
path=folder/(digest+'.json');reason='coach_provider_failed';failure=None;request_id=uuid.uuid4().hex[:12]
|
| 200 |
def generate(attempt,feedback):
|
| 201 |
usage=Usage();started=time.monotonic()
|
| 202 |
try:
|
|
|
|
| 206 |
response=client.models.generate_content(model=settings.video_review_model,
|
| 207 |
contents=PROMPT+'\n'+canonical+feedback,config=types.GenerateContentConfig(temperature=0,
|
| 208 |
max_output_tokens=settings.video_review_max_output_tokens,
|
| 209 |
+
response_mime_type='application/json',response_json_schema=provider_schema(),
|
| 210 |
thinking_config=types.ThinkingConfig(thinking_level='low')))
|
| 211 |
u=response.usage_metadata
|
| 212 |
usage=Usage(input_tokens=(u.prompt_token_count or 0) if u else 0,
|
|
|
|
| 244 |
group.score=reviews[group.key]['score'];group.coaching=reviews[group.key]['coaching']
|
| 245 |
else:group.score.reason_code='no_available_measurements'
|
| 246 |
temporary=path.with_suffix('.tmp');temporary.write_text(raw);temporary.replace(path)
|
| 247 |
+
except Exception as error:
|
| 248 |
# Keep the measurements, and never invent a default score on failure.
|
| 249 |
+
code=getattr(error,'code',None)
|
| 250 |
+
reason=f'coach_provider_http_{code}' if isinstance(code,int) and 100<=code<=599 else 'coach_review_error_'+type(error).__name__.lower()
|
| 251 |
+
message=getattr(error,'message',None)
|
| 252 |
+
failure=message if isinstance(message,str) else type(error).__name__
|
| 253 |
+
for secret in settings.secrets:failure=failure.replace(secret,'[redacted]')
|
| 254 |
+
failure=' '.join(failure.split())[:240]
|
| 255 |
finally:
|
| 256 |
for group in groups:
|
| 257 |
+
if group.score.status=='pending' and group.score.reason_code=='review_pending':
|
| 258 |
+
group.score.reason_code=reason;group.score.failure_detail=failure
|
baseball_batting/sam_api.py
CHANGED
|
@@ -47,7 +47,8 @@ def register(app,service,authenticated):
|
|
| 47 |
coach.review_groups(payload.groups)
|
| 48 |
if any(g.score.status=='pending' and any(m.value is not None and m.status!='unavailable' for w in g.swings for m in w.measurements) for g in payload.groups):
|
| 49 |
raise HTTPException(503,{'code':'group_coaching_pending','message':'Group coaching can be retried without re-running SAM.',
|
| 50 |
-
'reasons':{g.key:g.score.reason_code for g in payload.groups if g.score.status=='pending'}
|
|
|
|
| 51 |
return SamGroupReviewResponse(groups=[{'key':g.key,'score':g.score,'coaching':g.coaching} for g in payload.groups])
|
| 52 |
finally:review_lock.release()
|
| 53 |
|
|
|
|
| 47 |
coach.review_groups(payload.groups)
|
| 48 |
if any(g.score.status=='pending' and any(m.value is not None and m.status!='unavailable' for w in g.swings for m in w.measurements) for g in payload.groups):
|
| 49 |
raise HTTPException(503,{'code':'group_coaching_pending','message':'Group coaching can be retried without re-running SAM.',
|
| 50 |
+
'reasons':{g.key:g.score.reason_code for g in payload.groups if g.score.status=='pending'},
|
| 51 |
+
'details':{g.key:g.score.failure_detail for g in payload.groups if g.score.status=='pending' and g.score.failure_detail}})
|
| 52 |
return SamGroupReviewResponse(groups=[{'key':g.key,'score':g.score,'coaching':g.coaching} for g in payload.groups])
|
| 53 |
finally:review_lock.release()
|
| 54 |
|
baseball_batting/sam_batting_contract.py
CHANGED
|
@@ -199,6 +199,7 @@ class GroupScore(Strict):
|
|
| 199 |
aspects: list[ScoreAspect] = Field(default_factory=list, max_length=3)
|
| 200 |
reason_code: str | None = None
|
| 201 |
accuracy_validated: Literal[False] = False
|
|
|
|
| 202 |
notice: str = 'An estimated AI coaching judgment from the supplied measurements, not a validated performance benchmark.'
|
| 203 |
|
| 204 |
|
|
|
|
| 199 |
aspects: list[ScoreAspect] = Field(default_factory=list, max_length=3)
|
| 200 |
reason_code: str | None = None
|
| 201 |
accuracy_validated: Literal[False] = False
|
| 202 |
+
failure_detail: str | None = Field(default=None, max_length=240)
|
| 203 |
notice: str = 'An estimated AI coaching judgment from the supplied measurements, not a validated performance benchmark.'
|
| 204 |
|
| 205 |
|
docs/sam-batting-result.schema.json
CHANGED
|
@@ -320,6 +320,19 @@
|
|
| 320 |
"title": "Accuracy Validated",
|
| 321 |
"type": "boolean"
|
| 322 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 323 |
"notice": {
|
| 324 |
"default": "An estimated AI coaching judgment from the supplied measurements, not a validated performance benchmark.",
|
| 325 |
"title": "Notice",
|
|
|
|
| 320 |
"title": "Accuracy Validated",
|
| 321 |
"type": "boolean"
|
| 322 |
},
|
| 323 |
+
"failure_detail": {
|
| 324 |
+
"anyOf": [
|
| 325 |
+
{
|
| 326 |
+
"maxLength": 240,
|
| 327 |
+
"type": "string"
|
| 328 |
+
},
|
| 329 |
+
{
|
| 330 |
+
"type": "null"
|
| 331 |
+
}
|
| 332 |
+
],
|
| 333 |
+
"default": null,
|
| 334 |
+
"title": "Failure Detail"
|
| 335 |
+
},
|
| 336 |
"notice": {
|
| 337 |
"default": "An estimated AI coaching judgment from the supplied measurements, not a validated performance benchmark.",
|
| 338 |
"title": "Notice",
|
docs/sam-group-review.schema.json
CHANGED
|
@@ -321,6 +321,19 @@
|
|
| 321 |
"title": "Accuracy Validated",
|
| 322 |
"type": "boolean"
|
| 323 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 324 |
"notice": {
|
| 325 |
"default": "An estimated AI coaching judgment from the supplied measurements, not a validated performance benchmark.",
|
| 326 |
"title": "Notice",
|
|
@@ -1023,6 +1036,19 @@
|
|
| 1023 |
"title": "Accuracy Validated",
|
| 1024 |
"type": "boolean"
|
| 1025 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1026 |
"notice": {
|
| 1027 |
"default": "An estimated AI coaching judgment from the supplied measurements, not a validated performance benchmark.",
|
| 1028 |
"title": "Notice",
|
|
|
|
| 321 |
"title": "Accuracy Validated",
|
| 322 |
"type": "boolean"
|
| 323 |
},
|
| 324 |
+
"failure_detail": {
|
| 325 |
+
"anyOf": [
|
| 326 |
+
{
|
| 327 |
+
"maxLength": 240,
|
| 328 |
+
"type": "string"
|
| 329 |
+
},
|
| 330 |
+
{
|
| 331 |
+
"type": "null"
|
| 332 |
+
}
|
| 333 |
+
],
|
| 334 |
+
"default": null,
|
| 335 |
+
"title": "Failure Detail"
|
| 336 |
+
},
|
| 337 |
"notice": {
|
| 338 |
"default": "An estimated AI coaching judgment from the supplied measurements, not a validated performance benchmark.",
|
| 339 |
"title": "Notice",
|
|
|
|
| 1036 |
"title": "Accuracy Validated",
|
| 1037 |
"type": "boolean"
|
| 1038 |
},
|
| 1039 |
+
"failure_detail": {
|
| 1040 |
+
"anyOf": [
|
| 1041 |
+
{
|
| 1042 |
+
"maxLength": 240,
|
| 1043 |
+
"type": "string"
|
| 1044 |
+
},
|
| 1045 |
+
{
|
| 1046 |
+
"type": "null"
|
| 1047 |
+
}
|
| 1048 |
+
],
|
| 1049 |
+
"default": null,
|
| 1050 |
+
"title": "Failure Detail"
|
| 1051 |
+
},
|
| 1052 |
"notice": {
|
| 1053 |
"default": "An estimated AI coaching judgment from the supplied measurements, not a validated performance benchmark.",
|
| 1054 |
"title": "Notice",
|
tests/test_sam_group_scoring.py
CHANGED
|
@@ -146,3 +146,37 @@ def test_standalone_review_rejects_wrong_group_keys_and_units():
|
|
| 146 |
groups=group_fixture();SamGroupReviewRequest(groups=groups)
|
| 147 |
groups[0].swings[0].measurements[0].unit='ms'
|
| 148 |
with pytest.raises(ValueError):SamGroupReviewRequest(groups=groups)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
groups=group_fixture();SamGroupReviewRequest(groups=groups)
|
| 147 |
groups[0].swings[0].measurements[0].unit='ms'
|
| 148 |
with pytest.raises(ValueError):SamGroupReviewRequest(groups=groups)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def test_actual_sdk_serializes_inline_provider_schema():
|
| 152 |
+
import httpx
|
| 153 |
+
from google import genai
|
| 154 |
+
from google.genai import types
|
| 155 |
+
from ai_coach.group_review import provider_schema
|
| 156 |
+
captured=[]
|
| 157 |
+
def handler(request):
|
| 158 |
+
captured.append(json.loads(request.content))
|
| 159 |
+
return httpx.Response(200,json={'candidates':[{'content':{'parts':[{'text':'{"groups":[]}'}]}}]})
|
| 160 |
+
with genai.Client(api_key='fixture-not-a-key',http_options=types.HttpOptions(client_args={'transport':httpx.MockTransport(handler)})) as client:
|
| 161 |
+
client.models.generate_content(model='gemini-3.8-flash',contents='Fixture',config=types.GenerateContentConfig(
|
| 162 |
+
response_mime_type='application/json',response_json_schema=provider_schema()))
|
| 163 |
+
wire=json.dumps(captured[0]['generationConfig']['responseJsonSchema'])
|
| 164 |
+
assert '$defs' not in wire and '$ref' not in wire and 'minItems' not in wire
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def test_provider_error_details_are_typed_and_redact_the_key(tmp_path,monkeypatch):
|
| 168 |
+
from google import genai
|
| 169 |
+
from pydantic import SecretStr
|
| 170 |
+
class ProviderError(Exception):
|
| 171 |
+
code=429
|
| 172 |
+
message='Rejected request using fixture-not-a-key'
|
| 173 |
+
class Client:
|
| 174 |
+
def __init__(self,**kwargs):self.models=self
|
| 175 |
+
def __enter__(self):return self
|
| 176 |
+
def __exit__(self,*a):pass
|
| 177 |
+
def generate_content(self,**kwargs):raise ProviderError()
|
| 178 |
+
monkeypatch.setattr(genai,'Client',Client)
|
| 179 |
+
service=CoachService(Settings(_env_file=None,google_api_key=SecretStr('fixture-not-a-key'),cache_path=tmp_path/'cache.db',log_dir=tmp_path/'logs'))
|
| 180 |
+
groups=group_fixture();service.review_groups(groups)
|
| 181 |
+
assert all(g.score.reason_code=='coach_provider_http_429' for g in groups)
|
| 182 |
+
assert all('fixture-not-a-key' not in g.score.failure_detail and '[redacted]' in g.score.failure_detail for g in groups)
|