File size: 27,632 Bytes
f1b0176 0d1ea73 f1b0176 a1e6f13 0d1ea73 f1b0176 56f7955 f1b0176 56f7955 f1b0176 56f7955 f1b0176 56f7955 f1b0176 56f7955 6ab2085 56f7955 f1b0176 0d1ea73 a1e6f13 0d1ea73 781cd97 6ab2085 f1b0176 6ab2085 f1b0176 6ab2085 f1b0176 6ab2085 f1b0176 56f7955 f1b0176 56f7955 f1b0176 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 | import json
import unittest
from unittest.mock import patch
from training_coach.parser import (
PARSER_FALLBACK_MODEL,
PARSER_LOG_PARSED_JSON_ENV_VAR,
PARSER_LOG_RESPONSES_ENV_VAR,
PARSER_MODEL,
apply_follow_up_triggers,
build_parser_messages,
expected_response_format,
normalize_parsed_check_in,
parse_model_response,
)
from training_coach.models import CheckIn, FollowUpQuestion, PainIssue, ParsedCheckIn
class ParserTest(unittest.TestCase):
def test_parser_model_choice_is_locked(self):
self.assertEqual(PARSER_MODEL, "Qwen/Qwen2.5-1.5B-Instruct")
self.assertEqual(PARSER_FALLBACK_MODEL, "Qwen/Qwen3-4B")
def test_build_parser_messages_includes_response_shape_and_raw_text(self):
messages = build_parser_messages("45 min, terrible night, low energy")
self.assertEqual(messages[0]["role"], "system")
self.assertIn("Return JSON only", messages[0]["content"])
self.assertIn("Do not rename fields or use synonyms", messages[0]["content"])
self.assertIn("Do not ask post-workout questions", messages[0]["content"])
self.assertIn("sleep_hours", messages[0]["content"])
self.assertIn("follow_up_items", messages[0]["content"])
self.assertIn("recent_endurance_run", messages[0]["content"])
self.assertIn("triceps_brachii", messages[0]["content"])
self.assertIn("exactly this shape", messages[1]["content"])
self.assertIn("sleep_quality", messages[1]["content"])
self.assertIn("pain_issues", messages[1]["content"])
self.assertIn("context_signals", messages[1]["content"])
self.assertIn('"gastrocnemius"', messages[1]["content"])
self.assertIn("Do not add extra keys", messages[1]["content"])
self.assertIn("45 min, terrible night, low energy", messages[1]["content"])
self.assertTrue(messages[1]["content"].endswith("/no_think"))
def test_expected_response_format_is_parsed_check_in_schema(self):
schema = expected_response_format()
self.assertEqual(schema["title"], "ParsedCheckIn")
self.assertIn("check_in", schema["properties"])
self.assertIn("follow_up_items", schema["properties"])
self.assertIn("follow_up_questions", schema["properties"])
self.assertIn("context_signals", schema["properties"])
def test_parse_model_response_accepts_poor_sleep_follow_up(self):
response = json.dumps(
{
"check_in": {
"raw_text": "45 min, terrible night, low energy",
"time_available_minutes": 45,
"energy_level": "low",
"sleep_quality": "poor",
"sleep_hours": None,
"pain_or_injury": "unsure",
},
"missing_fields": ["sleep_hours"],
"follow_up_items": [
{
"field": "sleep_hours",
"question": "How many hours did you sleep?",
"reason": "Sleep quality is poor but sleep duration is missing.",
}
],
}
)
parsed = parse_model_response(response)
self.assertEqual(parsed.check_in.sleep_quality, "poor")
self.assertIsNone(parsed.check_in.sleep_hours)
self.assertIn("sleep_hours", parsed.missing_fields)
self.assertEqual(parsed.follow_up_questions, ["How many hours did you sleep?"])
def test_parse_model_response_lifts_top_level_keys_misplaced_in_check_in(self):
response = json.dumps(
{
"check_in": {
"raw_text": "45 min, terrible night",
"time_available_minutes": 45,
"sleep_quality": "poor",
"pain_or_injury": "no",
"missing_fields": ["sleep_hours"],
"follow_up_items": [
{
"field": "sleep_hours",
"question": "How many hours did you sleep?",
"reason": "Sleep quality is poor but hours are missing.",
}
],
"follow_up_questions": ["How many hours did you sleep?"],
"context_signals": [],
"notes": "check-in note stays here",
}
}
)
parsed = parse_model_response(response)
self.assertEqual(parsed.check_in.time_available_minutes, 45)
self.assertEqual(parsed.check_in.notes, "check-in note stays here")
self.assertIn("sleep_hours", parsed.missing_fields)
self.assertEqual(parsed.follow_up_questions, ["How many hours did you sleep?"])
def test_parse_model_response_drops_unknown_keys_everywhere(self):
response = json.dumps(
{
"check_in": {
"raw_text": "45 min, tricep ache, ran a 10k yesterday",
"time_available_minutes": 45,
"pain_or_injury": "yes",
"pain_issues": [
{
"affected_muscle": "triceps_brachii",
"severity": "mild",
"notes": "tricep ache",
"side": "left",
}
],
"warmup_done": True,
},
"training_recommendation": "go lighter today",
"follow_up_items": [
{
"field": "sleep_hours",
"question": "How many hours did you sleep?",
"reason": "Sleep info missing.",
"priority": 1,
}
],
"context_signals": [
{
"label": "recent_endurance_run",
"evidence": "ran a 10k",
"follow_up_question": "",
"confidence": 0.9,
}
],
}
)
parsed = parse_model_response(response)
self.assertEqual(parsed.check_in.time_available_minutes, 45)
self.assertEqual(
parsed.check_in.pain_issues[0].affected_muscle, "triceps_brachii"
)
self.assertEqual(parsed.follow_up_items[0].field, "sleep_hours")
self.assertEqual(parsed.context_signals[0].label, "recent_endurance_run")
def test_parse_model_response_coerces_invalid_nested_values(self):
response = json.dumps(
{
"check_in": {
"raw_text": "30 min, shoulder pain",
"time_available_minutes": -5,
"sleep_hours": 99,
"pain_or_injury": "yes",
"pain_issues": [
{
"affected_muscle": "left_shoulder",
"severity": "terrible",
"notes": "",
}
],
},
"follow_up_items": [
{"field": "shoulder", "question": "Which part of the shoulder?", "reason": ""},
{"field": "energy_level", "question": "", "reason": "no question"},
],
"context_signals": [
{"label": "ran_marathon", "evidence": "mentioned a run", "follow_up_question": ""},
{"label": "travel", "evidence": "", "follow_up_question": ""},
],
}
)
parsed = parse_model_response(response)
self.assertIsNone(parsed.check_in.time_available_minutes)
self.assertIsNone(parsed.check_in.sleep_hours)
issue = parsed.check_in.pain_issues[0]
self.assertIsNone(issue.affected_muscle)
self.assertEqual(issue.severity, "unsure")
self.assertTrue(issue.notes)
self.assertEqual(len(parsed.follow_up_items), 1)
self.assertEqual(parsed.follow_up_items[0].field, "other")
self.assertEqual(len(parsed.context_signals), 1)
self.assertEqual(parsed.context_signals[0].label, "other")
def test_parse_model_response_nulls_invalid_check_in_enums(self):
response = json.dumps(
{
"check_in": {
"raw_text": "30 min, stressed from work",
"time_available_minutes": 30,
"energy_level": "neutral",
"sleep_quality": "great",
"mood_stress": "stressed",
"pain_or_injury": "maybe",
}
}
)
parsed = parse_model_response(response)
self.assertIsNone(parsed.check_in.energy_level)
self.assertIsNone(parsed.check_in.sleep_quality)
self.assertEqual(parsed.check_in.mood_stress, "stressed")
self.assertEqual(parsed.check_in.pain_or_injury, "unsure")
def test_parse_model_response_drops_bare_field_names_in_follow_up_questions(self):
response = json.dumps(
{
"check_in": {
"raw_text": "60 min, slept great, no pain",
"time_available_minutes": 60,
"sleep_quality": "good",
"pain_or_injury": "no",
},
"follow_up_questions": ["energy_level", "mood_stress"],
}
)
parsed = parse_model_response(response)
self.assertEqual(parsed.follow_up_questions, [])
def test_parse_model_response_accepts_adjacent_context_signal(self):
response = json.dumps(
{
"check_in": {
"raw_text": "Yesterday I ran a 10k.",
"pain_or_injury": "unsure",
},
"context_signals": [
{
"label": "recent_endurance_run",
"evidence": "Yesterday I ran a 10k.",
"follow_up_question": (
"How are your legs and energy after yesterday's run?"
),
}
],
"follow_up_questions": [
"How are your legs and energy after yesterday's run?"
],
}
)
parsed = parse_model_response(response)
self.assertEqual(parsed.context_signals[0].label, "recent_endurance_run")
self.assertEqual(
parsed.context_signals[0].follow_up_question,
"How are your legs and energy after yesterday's run?",
)
def test_parse_model_response_accepts_pain_issues_per_problem_area(self):
response = json.dumps(
{
"check_in": {
"raw_text": "Right tricep hurts and my hamstring is tight.",
"pain_or_injury": "yes",
"pain_issues": [
{
"affected_muscle": "triceps_brachii",
"severity": "moderate",
"notes": "Right tricep hurts.",
},
{
"affected_muscle": "hamstrings",
"severity": "mild",
"notes": "Hamstring is tight.",
},
],
},
"follow_up_questions": [
"Is the hamstring tightness normal soreness or pain?"
],
}
)
parsed = parse_model_response(response)
self.assertEqual(len(parsed.check_in.pain_issues), 2)
self.assertEqual(
parsed.check_in.pain_issues[0].affected_muscle,
"triceps_brachii",
)
def test_parse_model_response_fills_obvious_missing_affected_muscle(self):
response = json.dumps(
{
"check_in": {
"raw_text": (
"My right tricep hurts today, probably moderate. "
"I have about an hour."
),
"time_available_minutes": 60,
"pain_or_injury": "yes",
"pain_issues": [
{
"severity": "moderate",
"notes": "Right tricep hurts today.",
}
],
},
}
)
parsed = parse_model_response(response)
self.assertEqual(
parsed.check_in.pain_issues[0].affected_muscle,
"triceps_brachii",
)
def test_normalize_parsed_check_in_creates_pain_issue_from_bicep_tore(self):
parsed = normalize_parsed_check_in(
ParsedCheckIn(check_in=CheckIn(raw_text="My bicep tore."))
)
self.assertEqual(parsed.check_in.pain_or_injury, "yes")
self.assertEqual(len(parsed.check_in.pain_issues), 1)
self.assertEqual(
parsed.check_in.pain_issues[0].affected_muscle,
"biceps_brachii",
)
def test_normalize_removes_unsupported_run_follow_up_and_maps_glutes(self):
parsed = normalize_parsed_check_in(
ParsedCheckIn(
check_in=CheckIn(
raw_text=(
"i feel tired, and i have 45 minutes to exercise. "
"My glutes are in pain, not recovered."
),
time_available_minutes=45,
pain_or_injury="yes",
pain_issues=[
PainIssue(
affected_muscle=None,
severity="unsure",
notes="glutes are in pain, not recovered",
)
],
),
context_signals=[
{
"label": "recent_endurance_run",
"evidence": "not recovered",
"follow_up_question": "How are your legs and energy after the run?",
}
],
follow_up_questions=[
"How are your legs and energy after the run?",
"You mentioned a body area. Is it pain, injury, normal soreness, or just a note?",
],
follow_up_items=[
FollowUpQuestion(
field="context_signals",
question="How are your legs and energy after the run?",
reason="The model thought the user had run.",
),
FollowUpQuestion(
field="pain_issues",
question=(
"You mentioned a body area. Is it pain, injury, "
"normal soreness, or just a note?"
),
reason="The model thought the body area was unclear.",
),
],
)
)
self.assertEqual(parsed.context_signals, [])
self.assertEqual(parsed.follow_up_items, [])
self.assertEqual(parsed.follow_up_questions, [])
self.assertEqual(
parsed.check_in.pain_issues[0].affected_muscle,
"gluteus_maximus",
)
def test_normalize_maps_each_pain_issue_from_its_own_notes(self):
parsed = normalize_parsed_check_in(
ParsedCheckIn(
check_in=CheckIn(
raw_text=(
"my calves are cooked and in pain from last round. "
"my biceps are a bit in pain in contraction."
),
pain_or_injury="yes",
pain_issues=[
PainIssue(
affected_muscle=None,
severity="unsure",
notes="calves are cooked and in pain from last round",
),
PainIssue(
affected_muscle=None,
severity="unsure",
notes="biceps are a bit in pain in contraction",
),
],
)
)
)
self.assertEqual(
parsed.check_in.pain_issues[0].affected_muscle,
"gastrocnemius",
)
self.assertEqual(
parsed.check_in.pain_issues[1].affected_muscle,
"biceps_brachii",
)
def test_normalize_parsed_check_in_leaves_unclear_muscle_unknown(self):
parsed = normalize_parsed_check_in(
ParsedCheckIn(
check_in=CheckIn(
raw_text="My arm feels weird.",
pain_issues=[
PainIssue(
affected_muscle=None,
severity="unsure",
notes="Arm feels weird.",
)
],
)
)
)
self.assertIsNone(parsed.check_in.pain_issues[0].affected_muscle)
def test_follow_up_triggers_keep_model_sleep_question_when_missing(self):
parsed = apply_follow_up_triggers(
ParsedCheckIn(
check_in=CheckIn(raw_text="Rough night, maybe a nap later."),
missing_fields=["sleep_hours"],
follow_up_items=[
FollowUpQuestion(
field="sleep_hours",
question="How many hours did you sleep?",
reason="Sleep was rough and duration is missing.",
)
],
)
)
self.assertIn("sleep_hours", parsed.missing_fields)
self.assertEqual(parsed.follow_up_questions, ["How many hours did you sleep?"])
def test_follow_up_triggers_keep_only_missing_sleep_hours_question(self):
parsed = apply_follow_up_triggers(
ParsedCheckIn(
check_in=CheckIn(
raw_text="Sleep was meh.",
sleep_quality="okay",
sleep_hours=None,
),
follow_up_items=[
FollowUpQuestion(
field="sleep_quality",
question="Was your sleep poor, okay, or good?",
reason="The model duplicated an answered sleep field.",
),
FollowUpQuestion(
field="sleep_hours",
question="How many hours did you sleep?",
reason="Duration is still missing.",
),
],
)
)
self.assertEqual(parsed.follow_up_questions, ["How many hours did you sleep?"])
def test_follow_up_triggers_do_not_ask_sleep_when_sleep_data_is_complete(self):
parsed = apply_follow_up_triggers(
ParsedCheckIn(
check_in=CheckIn(
raw_text=(
"im ok, sleep was meh, and i have 30 minutos to exercise. "
"I slept 5 hours, it was okay."
),
sleep_quality="okay",
sleep_hours=5,
),
missing_fields=["sleep_hours"],
follow_up_questions=[
"How many hours did you sleep?",
"How many hours did you sleep, and was the sleep poor, okay, or good?",
],
follow_up_items=[
FollowUpQuestion(
field="sleep_hours",
question="How many hours did you sleep?",
reason="The model duplicated an answered sleep field.",
)
],
)
)
self.assertNotIn("sleep_hours", parsed.missing_fields)
self.assertEqual(parsed.follow_up_items, [])
self.assertEqual(parsed.follow_up_questions, [])
def test_normalize_parsed_check_in_infers_meh_sleep_as_okay(self):
parsed = normalize_parsed_check_in(
ParsedCheckIn(
check_in=CheckIn(
raw_text=(
"im ok, sleep was meh, and i have 30 minutos to exercise. "
"I slept 5 hours, it was fine."
),
sleep_hours=5,
),
follow_up_questions=[
"How many hours did you sleep, and was the sleep poor, okay, or good?"
],
)
)
self.assertEqual(parsed.check_in.sleep_quality, "okay")
self.assertEqual(parsed.follow_up_questions, [])
def test_follow_up_triggers_do_not_invent_body_area_questions(self):
parsed = apply_follow_up_triggers(
ParsedCheckIn(check_in=CheckIn(raw_text="My shoulder feels odd today."))
)
self.assertEqual(parsed.follow_up_questions, [])
def test_follow_up_triggers_keep_model_activity_question_when_activity_is_present(self):
parsed = apply_follow_up_triggers(
ParsedCheckIn(
check_in=CheckIn(raw_text="I played soccer yesterday."),
follow_up_items=[
FollowUpQuestion(
field="readiness",
question=(
"How did soccer affect your energy, soreness, "
"and readiness today?"
),
reason="Recent sport may affect today's training readiness.",
)
],
)
)
self.assertIn(
"How did soccer affect your energy, soreness, and readiness today?",
parsed.follow_up_questions,
)
def test_follow_up_triggers_are_deduplicated(self):
parsed = apply_follow_up_triggers(
ParsedCheckIn(
check_in=CheckIn(raw_text="Slept badly last night."),
follow_up_items=[
FollowUpQuestion(
field="sleep_hours",
question="How many hours did you sleep?",
reason="Sleep duration is missing.",
),
FollowUpQuestion(
field="sleep_hours",
question="How many hours did you sleep?",
reason="Duplicate from model.",
),
],
)
)
self.assertEqual(
parsed.follow_up_questions.count("How many hours did you sleep?"),
1,
)
def test_parse_model_response_rejects_invalid_json(self):
with self.assertRaises(ValueError):
parse_model_response("not json")
def test_parse_model_response_logs_invalid_json_when_debug_flag_is_enabled(self):
response_text = "not json"
with patch.dict(
"os.environ",
{PARSER_LOG_RESPONSES_ENV_VAR: "1"},
clear=True,
), self.assertLogs("training_coach.parser", level="ERROR") as logs:
with self.assertRaises(ValueError):
parse_model_response(response_text)
output = "\n".join(logs.output)
self.assertIn("event=parser_invalid_json_response", output)
self.assertIn(repr(response_text), output)
def test_parse_model_response_logs_parsed_json_when_debug_flag_is_enabled(self):
response = json.dumps(
{
"check_in": {
"raw_text": "60 min",
"time_available_minutes": 60,
"pain_or_injury": "unsure",
}
}
)
with patch.dict(
"os.environ",
{PARSER_LOG_PARSED_JSON_ENV_VAR: "1"},
clear=True,
), self.assertLogs("training_coach.parser", level="INFO") as logs:
parse_model_response(response)
output = "\n".join(logs.output)
self.assertIn("event=parser_json_loaded", output)
self.assertIn("event=parser_validated_json", output)
self.assertIn("event=parser_normalized_json", output)
def test_negated_pain_mentions_do_not_force_injury(self):
for text in (
"about my calves, nothing hurts",
"60 minutes, slept great, feeling strong, no pain",
"shoulder doesn't hurt anymore",
"pain free today",
):
parsed = ParsedCheckIn(
check_in=CheckIn(raw_text=text, pain_or_injury="no")
)
normalized = normalize_parsed_check_in(parsed)
self.assertEqual(
normalized.check_in.pain_or_injury, "no", msg=repr(text)
)
self.assertEqual(normalized.check_in.pain_issues, [], msg=repr(text))
def test_positive_pain_mentions_still_force_injury(self):
for text in (
"my tricep aches a bit",
"no pain except my knee hurts",
"left shoulder hurts but back doesn't hurt",
):
parsed = ParsedCheckIn(
check_in=CheckIn(raw_text=text, pain_or_injury="no")
)
normalized = normalize_parsed_check_in(parsed)
self.assertEqual(
normalized.check_in.pain_or_injury, "yes", msg=repr(text)
)
def test_parse_model_response_drops_training_actions(self):
response = json.dumps(
{
"check_in": {"raw_text": "Yesterday I ran a 10k."},
"training_action": "skip squats",
}
)
parsed = parse_model_response(response)
# The invented key is dropped; no training decision reaches the engine.
self.assertNotIn("training_action", parsed.model_dump())
def test_parse_model_response_drops_synonym_keys_then_infers(self):
response = json.dumps(
{
"check_in": {
"raw_text": "I had a terrible night.",
"rest": "suboptimal",
"pain_or_injury": "unsure",
}
}
)
parsed = parse_model_response(response)
# "rest" is dropped rather than rejected; deterministic inference
# still reads "terrible" from the raw text.
self.assertEqual(parsed.check_in.sleep_quality, "poor")
def test_parse_model_response_coerces_synonym_values_to_null_then_infers(self):
response = json.dumps(
{
"check_in": {
"raw_text": "I had a terrible night.",
"sleep_quality": "suboptimal",
"pain_or_injury": "unsure",
}
}
)
parsed = parse_model_response(response)
# "suboptimal" is nulled rather than rejected, then deterministic
# inference reads "terrible" from the raw text.
self.assertEqual(parsed.check_in.sleep_quality, "poor")
if __name__ == "__main__":
unittest.main()
|