Spaces:
Sleeping
Sleeping
File size: 46,352 Bytes
fdfe81a | 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 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 | """Python orchestrator for the agentic brand review (NOT SDK handoffs).
`run_audit(ctx, job_id)` drives the three agents:
1. Pre-scans every slide for the fixed must-flag terms (DRAFT, TW question,
Page to be updated) using ``services.markers.find_text_markers_pure``
directly. Hits are persisted in ``marker_hits[slide_n]`` and passed into
each Slide Reviewer call as part of ``SlideBriefing``.
2. Runs the Slide Reviewer Agent in parallel across all slides, capped at
``MAX_CONCURRENT_SLIDES`` (5) by ``asyncio.Semaphore``.
3. Runs the Deck Consistency Agent once.
4. Runs the Lead Auditor Agent once over the collected slide + deck findings;
the agent returns a draft :class:`FinalAuditResult`.
5. Walks every must-flag hit and injects a deterministic ``safety_net``
finding for any hit the upstream agents did not surface. This is the
demo's must-flag guarantee β it lives in Python, not the LLM.
6. Validates each finding's evidence and category at the boundary; tags
``finding_meta.must_flag = True`` on agent findings whose evidence
overlaps a marker hit's context window.
7. Records per-slide errors in ``FinalAuditResult.errors``. If any slide had
no successful agent output, the audit ends ``partial`` (the API layer
reads ``errors``); the runner does NOT re-raise.
A small retry helper wraps every ``Runner.run`` call: up to 4 attempts on
``RateLimitError``, ``APITimeoutError``, and ``APIStatusError(>=500)``;
permanent 4xx (non-429) errors propagate.
Public surface
--------------
* :func:`run_audit` β top-level coroutine. The API layer awaits this from
inside its job-processing background task.
* :func:`_run_with_retry` β exposed for unit tests.
* :class:`SlideBriefing`, :class:`ConsistencyBriefing`, :class:`MergeInput` β
the per-call inputs the Agents SDK serialises into the agent prompt.
"""
from __future__ import annotations
import asyncio
import json
import logging
import os
import random
import re
import time
from dataclasses import asdict, dataclass, is_dataclass
from pathlib import Path
from typing import Any, Awaitable, Callable
import openai
from agents import Runner
from agents.context import AuditContext
from agents.consistency import deck_consistency
from agents.lead_auditor import lead_auditor
from agents.output_schemas import (
DeckFindings,
FindingExtended,
FindingMeta,
FinalAuditResult,
SeverityCounts,
SlideEnvelopeExtended,
SlideFindings,
)
from agents.slide_bundle import (
build_rubric_full,
build_slide_bundle,
bundle_to_prompt_payload,
)
from agents.slide_reviewer import (
SLIDE_REVIEWER_MODE_AGENTIC,
SLIDE_REVIEWER_MODE_SINGLE_SHOT,
get_slide_reviewer,
get_slide_reviewer_mode,
slide_reviewer,
)
from services.confidentiality import ConfidentialityCheck, check_confidentiality_pure
from services.event_log import append_event
from services.markers import Hit, find_text_markers_pure
from services.rate_limit import (
DECK_CONSISTENCY_EST_TOKENS,
LEAD_AUDITOR_EST_TOKENS,
SLIDE_REVIEW_EST_TOKENS,
TokenRateLimiter,
get_default_limiter,
)
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
MUST_FLAG_TERMS: list[str] = ["DRAFT", "TW question", "Page to be updated"]
def _int_env(key: str, default: int) -> int:
raw = os.environ.get(key, "")
if not raw:
return default
try:
return int(raw)
except ValueError:
logger.warning("Invalid %s=%r β falling back to %d", key, raw, default)
return default
# Concurrency cap is env-tunable. The rate limiter is the *primary* throttle β
# this semaphore is a fail-safe in case the limiter mis-estimates and the
# pipeline tries to fan out beyond the API's connection-level tolerance.
_REQUESTED_CONCURRENT_SLIDES: int = _int_env("OPENAI_REVIEW_CONCURRENCY", 2)
_HARD_MAX_CONCURRENT_SLIDES: int = _int_env("OPENAI_REVIEW_CONCURRENCY_HARD_CAP", 2)
MAX_CONCURRENT_SLIDES: int = max(
1, min(_REQUESTED_CONCURRENT_SLIDES, _HARD_MAX_CONCURRENT_SLIDES)
)
MAX_TURNS_SLIDE_REVIEWER: int = 15
# In single-shot mode the agent has no tools; one turn is exactly what we
# want and the SDK will reject anything > 1 if a tool call is requested.
MAX_TURNS_SLIDE_REVIEWER_SINGLE_SHOT: int = 1
MAX_TURNS_DECK_CONSISTENCY: int = 10
MAX_TURNS_LEAD_AUDITOR: int = 10
# Bumped from 4 β 5 attempts so transient bursts (which can run 3-4 deep
# during the first minute of a large deck) get more slack before failing.
MAX_RETRY_ATTEMPTS: int = 5
# Exponential backoff base delays (seconds): 2, 4, 8, 16, 30 (capped).
# These run *before* attempts 2..6 β first attempt is always immediate.
_BACKOFF_DELAYS: tuple[float, ...] = (2.0, 4.0, 8.0, 16.0, 30.0)
_BACKOFF_MAX_SECONDS: float = 30.0
# OpenAI's RateLimitError message often embeds a "Please try again in 3.87s"
# hint computed from headers. When present, honour it instead of guessing.
_RETRY_AFTER_RE = re.compile(
r"try again in ([\d.]+)\s*(ms|s)", re.IGNORECASE
)
# ---------------------------------------------------------------------------
# Per-call agent inputs
# ---------------------------------------------------------------------------
@dataclass
class SlideBriefing:
"""Input passed to one Slide Reviewer Agent invocation."""
slide_number: int
marker_hits: list[Hit]
@dataclass
class ConsistencyBriefing:
"""Input passed to the single Deck Consistency Agent invocation."""
slide_count: int
@dataclass
class MergeInput:
"""Input passed to the single Lead Auditor Agent invocation."""
job_id: str
file_name: str
slide_count: int
slide_findings: list[SlideFindings]
deck_findings: DeckFindings
def _briefing_to_prompt(briefing: Any) -> str:
"""Serialise a dataclass briefing into a deterministic JSON prompt string.
The Agents SDK accepts ``str | list[TResponseInputItem] | RunState``. We
use a JSON string so the agent gets a single, predictable user message.
"""
if is_dataclass(briefing):
payload = asdict(briefing)
else:
payload = briefing # already a dict / Pydantic-ish
return json.dumps(payload, default=_json_default, ensure_ascii=False)
def _json_default(obj: Any) -> Any:
"""JSON encoder fallback for Hit / Pydantic models."""
if hasattr(obj, "model_dump"):
return obj.model_dump()
if is_dataclass(obj):
return asdict(obj)
raise TypeError(f"Cannot serialise {type(obj).__name__}")
# ---------------------------------------------------------------------------
# Single-shot multimodal input construction
# ---------------------------------------------------------------------------
def _single_shot_input(bundle: Any) -> list[dict[str, Any]]:
"""Build the Agents-SDK ``input`` list for a single-shot review.
Returns a list with exactly one ``user`` message whose content has two
parts:
1. ``input_image`` β the rendered PNG as a base64 data URL (omitted
when the bundle has no image β e.g. soffice was unavailable).
2. ``input_text`` β the JSON-serialised bundle payload (without the
image bytes β those are the input_image part).
The shape matches the OpenAI Responses API's
``ResponseInputMessageContentList`` and is what the Agents SDK forwards
verbatim when ``input`` is a list of dicts.
"""
payload = bundle_to_prompt_payload(bundle)
text_part: dict[str, Any] = {
"type": "input_text",
"text": json.dumps(payload, default=_json_default, ensure_ascii=False),
}
content: list[dict[str, Any]] = []
if bundle.image_b64:
content.append(
{
"type": "input_image",
"detail": "auto",
"image_url": f"data:image/png;base64,{bundle.image_b64}",
}
)
content.append(text_part)
return [{"role": "user", "content": content}]
# ---------------------------------------------------------------------------
# Retry helper
# ---------------------------------------------------------------------------
def _is_retriable(exc: BaseException) -> bool:
"""True if *exc* is a transient OpenAI error worth retrying.
Includes ``APIConnectionError`` β the connection-reset pattern we saw in
the 33-slide audit ("connection error") happens when the server kills
a TCP socket mid-stream during heavy concurrency.
"""
if isinstance(exc, (
openai.RateLimitError,
openai.APITimeoutError,
openai.APIConnectionError,
)):
return True
if isinstance(exc, openai.APIStatusError):
status = getattr(exc, "status_code", None)
if status is not None and status >= 500:
return True
return False
def _retry_after_hint(exc: BaseException) -> float | None:
"""Extract a ``retry-after`` hint (seconds) from an OpenAI error.
OpenAI 429s typically embed the wait into the message body. Falls back
to the ``retry-after`` HTTP header when available. Returns ``None`` if
no hint can be parsed.
"""
msg = str(exc) if exc else ""
m = _RETRY_AFTER_RE.search(msg)
if m:
try:
value = float(m.group(1))
return value / 1000 if m.group(2).lower() == "ms" else value
except ValueError:
pass
# APIStatusError has a .response with headers in modern SDKs.
response = getattr(exc, "response", None)
if response is not None:
try:
header = response.headers.get("retry-after")
except Exception: # noqa: BLE001 β defensive against odd mocks
header = None
if header:
try:
return float(header)
except ValueError:
pass
return None
async def _run_with_retry(
coro_factory: Callable[[], Awaitable[Any]],
*,
label: str,
max_attempts: int = MAX_RETRY_ATTEMPTS,
sleep: Callable[[float], Awaitable[None]] = asyncio.sleep,
rng: Callable[[], float] = random.random,
) -> Any:
"""Run *coro_factory* with exponential backoff on retriable OpenAI errors.
Retries on ``RateLimitError``, ``APITimeoutError``,
``APIConnectionError`` and ``APIStatusError`` with ``status_code >= 500``.
All other errors propagate immediately.
Backoff strategy:
* If the error embeds a ``retry-after`` hint (parsed from message or
header), use ``hint + jitter`` β capped at :data:`_BACKOFF_MAX_SECONDS`.
* Otherwise, exponential backoff: 2s, 4s, 8s, 16s, 30s + jitter.
* Up to :data:`MAX_RETRY_ATTEMPTS` attempts (default 5).
The ``sleep`` and ``rng`` parameters are seams for unit tests so they can
pass a ``no_sleep`` and a deterministic RNG.
"""
last_exc: BaseException | None = None
for attempt in range(1, max_attempts + 1):
try:
return await coro_factory()
except BaseException as exc: # noqa: BLE001 β narrow with _is_retriable
last_exc = exc
if not _is_retriable(exc) or attempt >= max_attempts:
raise
hint = _retry_after_hint(exc)
if hint is not None:
base = min(hint, _BACKOFF_MAX_SECONDS)
else:
base = _BACKOFF_DELAYS[min(attempt - 1, len(_BACKOFF_DELAYS) - 1)]
jitter = rng()
wait = min(base + jitter, _BACKOFF_MAX_SECONDS)
logger.warning(
"%s: retriable error (%s) on attempt %d/%d β sleeping %.2fs%s",
label, type(exc).__name__, attempt, max_attempts, wait,
" (hint)" if hint is not None else "",
)
await sleep(wait)
# Defensive: should be unreachable.
assert last_exc is not None
raise last_exc
# ---------------------------------------------------------------------------
# Public orchestrator
# ---------------------------------------------------------------------------
def _model_for(agent: Any, default_env: str, fallback: str = "gpt-4o") -> str:
"""Return the model name used by *agent* for rate-limit bucketing.
The Agents SDK stores the model on the agent itself, but the agent
constructor pinned it at import time. We re-resolve from the env at
call time so per-agent overrides honoured at runtime β important for
tests that monkeypatch ``OPENAI_MODEL_*`` between scenarios.
"""
return os.environ.get(default_env) or os.environ.get("OPENAI_MODEL") or fallback
async def run_audit(
ctx: AuditContext,
job_id: str,
*,
file_name: str | None = None,
runner: Any = Runner,
on_slide_done: Callable[[int, int], None] | None = None,
job_dir: Path | None = None,
rate_limiter: TokenRateLimiter | None = None,
) -> FinalAuditResult:
"""Drive the agentic brand review and return the final audit result.
Parameters
----------
ctx:
The shared :class:`AuditContext` (parsed deck, render result, rubric).
job_id:
The audit job identifier β copied verbatim into the result envelope.
file_name:
Optional original PPTX file name; defaults to ``"deck.pptx"``.
runner:
Injection seam for tests β must expose an async ``run`` matching
``Runner.run``. Defaults to the SDK's :class:`Runner`.
on_slide_done:
Optional callback invoked after each slide reviewer settles (success
or exception). Receives ``(completed_count, total)`` where
``completed_count`` is the monotonically increasing number of slides
that have finished (not necessarily succeeded). Callback exceptions
are swallowed so they never crash the audit. An initial tick with
``(0, total)`` is fired before the gather begins so callers can
initialise their progress display.
job_dir:
Optional path to the job's on-disk directory. When supplied, the
runner appends per-slide ``slide-reviewed`` events to
``{job_dir}/events.jsonl`` so the SSE generator can stream them to
the client. Tests typically pass ``None``.
rate_limiter:
Optional :class:`TokenRateLimiter` override (test seam). Defaults
to the process-global limiter when ``None``.
"""
file_name = file_name or "deck.pptx"
slide_count = ctx.parsed_deck.slide_count
errors: list[str] = []
limiter = rate_limiter if rate_limiter is not None else get_default_limiter()
slide_model = _model_for(slide_reviewer, "OPENAI_MODEL_SLIDE", "gpt-4o-mini")
deck_model = _model_for(deck_consistency, "OPENAI_MODEL_DECK", "gpt-4o")
merge_model = _model_for(lead_auditor, "OPENAI_MODEL_MERGE", "gpt-4o")
# 1. Pre-scan must-flag markers (deterministic, unconditional).
marker_hits: dict[int, list[Hit]] = {
n: find_text_markers_pure(ctx.parsed_deck, n, MUST_FLAG_TERMS)
for n in range(1, slide_count + 1)
}
# 1b. Resolve slide-reviewer mode + cache deck-wide rubric snapshot once.
review_mode = get_slide_reviewer_mode()
active_slide_reviewer = get_slide_reviewer()
rubric_full = (
build_rubric_full(ctx.rubric)
if review_mode == SLIDE_REVIEWER_MODE_SINGLE_SHOT
else None
)
logger.info(
"slide_reviewer mode=%s, model=%s, max_turns=%d",
review_mode,
slide_model,
(
MAX_TURNS_SLIDE_REVIEWER_SINGLE_SHOT
if review_mode == SLIDE_REVIEWER_MODE_SINGLE_SHOT
else MAX_TURNS_SLIDE_REVIEWER
),
)
# 2. Slide reviewers in parallel, semaphore-bounded *and* TPM-budgeted.
semaphore = asyncio.Semaphore(MAX_CONCURRENT_SLIDES)
completed_counter = {"n": 0}
completed_lock = asyncio.Lock()
# Initial tick so the UI can show "Reviewed 0 of N" immediately.
if on_slide_done is not None:
try:
on_slide_done(0, slide_count)
except Exception: # noqa: BLE001 β callback failure must not crash audit
pass
async def review_one(slide_n: int) -> Any:
async with semaphore:
started = time.monotonic()
sf: SlideFindings | None = None
err: BaseException | None = None
# Build the agent input depending on the active mode.
if review_mode == SLIDE_REVIEWER_MODE_SINGLE_SHOT:
bundle = build_slide_bundle(
slide_n,
ctx.parsed_deck,
ctx.render_result,
ctx.rubric,
rubric_full=rubric_full,
include_image_b64=True,
marker_hits=marker_hits[slide_n],
)
slide_input: Any = _single_shot_input(bundle)
slide_max_turns = MAX_TURNS_SLIDE_REVIEWER_SINGLE_SHOT
else:
briefing = SlideBriefing(
slide_number=slide_n, marker_hits=marker_hits[slide_n]
)
slide_input = _briefing_to_prompt(briefing)
slide_max_turns = MAX_TURNS_SLIDE_REVIEWER
try:
# Rate-limit acquire happens *inside* the retry factory so a
# 429 can re-acquire on the next attempt (the prior reservation
# has aged out by then in the worst case).
async def _do_call():
# Throttling: rely on (a) the asyncio.Semaphore concurrency
# cap, (b) the OpenAI SDK's built-in max_retries, and
# (c) our _run_with_retry exponential backoff with retry-after
# parsing. The pre-call TokenRateLimiter was removed because
# its undercounting created more 429 noise than it prevented.
return await runner.run(
active_slide_reviewer,
input=slide_input,
context=ctx,
max_turns=slide_max_turns,
)
result = await _run_with_retry(
_do_call,
label=f"slide_reviewer[slide={slide_n}]",
)
sf = _extract_final_output(result, SlideFindings)
return result
except BaseException as exc: # noqa: BLE001
err = exc
raise
finally:
duration_ms = int((time.monotonic() - started) * 1000)
async with completed_lock:
completed_counter["n"] += 1
if on_slide_done is not None:
try:
on_slide_done(completed_counter["n"], slide_count)
except Exception: # noqa: BLE001 β callback failure must not crash audit
pass
# Append per-slide event for the SSE stream.
if job_dir is not None:
payload: dict[str, Any] = {
"slide_number": slide_n,
"duration_ms": duration_ms,
}
if err is not None:
payload["error"] = f"{type(err).__name__}: {err}"
payload["findings_count"] = 0
payload["max_severity"] = None
else:
findings = sf.findings if sf is not None else []
payload["findings_count"] = len(findings)
payload["max_severity"] = _max_severity(findings)
append_event(job_dir, "slide-reviewed", payload)
raw_slide_results: list[Any] = await asyncio.gather(
*[review_one(n) for n in range(1, slide_count + 1)],
return_exceptions=True,
)
slide_findings_by_n: dict[int, SlideFindings] = {}
for n, result in enumerate(raw_slide_results, start=1):
if isinstance(result, BaseException):
errors.append(f"slide {n}: {type(result).__name__}: {result}")
continue
sf = _extract_final_output(result, SlideFindings)
if sf is None:
errors.append(
f"slide {n}: agent returned no SlideFindings output"
)
continue
slide_findings_by_n[n] = sf
# 3. Deck consistency once.
deck_findings: DeckFindings
try:
deck_briefing = ConsistencyBriefing(slide_count=slide_count)
async def _deck_call():
return await runner.run(
deck_consistency,
input=_briefing_to_prompt(deck_briefing),
context=ctx,
max_turns=MAX_TURNS_DECK_CONSISTENCY,
)
deck_result = await _run_with_retry(_deck_call, label="deck_consistency")
df = _extract_final_output(deck_result, DeckFindings)
deck_findings = df if df is not None else DeckFindings(findings=[])
except BaseException as exc: # noqa: BLE001
errors.append(f"deck_consistency: {type(exc).__name__}: {exc}")
deck_findings = DeckFindings(findings=[])
# 4. Lead Auditor merge (best-effort β fall back to a Python merge).
lead_result: FinalAuditResult | None = None
try:
merge_input = MergeInput(
job_id=job_id,
file_name=file_name,
slide_count=slide_count,
slide_findings=list(slide_findings_by_n.values()),
deck_findings=deck_findings,
)
async def _merge_call():
return await runner.run(
lead_auditor,
input=_briefing_to_prompt(merge_input),
context=ctx,
max_turns=MAX_TURNS_LEAD_AUDITOR,
)
merged_raw = await _run_with_retry(_merge_call, label="lead_auditor")
lead_result = _extract_final_output(merged_raw, FinalAuditResult)
except BaseException as exc: # noqa: BLE001
errors.append(f"lead_auditor: {type(exc).__name__}: {exc}")
if lead_result is None:
# Python fallback merge β keeps the audit usable when Lead Auditor fails.
lead_result = _python_fallback_merge(
job_id=job_id,
file_name=file_name,
slide_count=slide_count,
slide_findings_by_n=slide_findings_by_n,
deck_findings=deck_findings,
)
# 5/6. Boundary validation, must_flag tagging, deterministic must-flag injection.
final = _finalise(
job_id=job_id,
file_name=file_name,
slide_count=slide_count,
lead_result=lead_result,
marker_hits=marker_hits,
ctx=ctx,
errors=errors,
)
return final
# ---------------------------------------------------------------------------
# Lead-auditor result extraction (handles both real RunResult and mocks)
# ---------------------------------------------------------------------------
_SEVERITY_RANK: dict[str, int] = {"low": 1, "medium": 2, "high": 3}
def _max_severity(findings: list[Any]) -> str | None:
"""Return the highest-severity label across a list of findings (or None)."""
best: str | None = None
best_rank = 0
for f in findings:
sev = getattr(f, "severity", None)
if sev is None and isinstance(f, dict):
sev = f.get("severity")
rank = _SEVERITY_RANK.get(str(sev or ""), 0)
if rank > best_rank:
best = str(sev)
best_rank = rank
return best
def _extract_final_output(result: Any, expected_type: type) -> Any:
"""Pull the structured output of an Agents SDK ``RunResult``.
The SDK stores the parsed ``output_type`` instance under
``result.final_output``. Tests may pass back a bare instance of the
expected type (e.g. a ``SlideFindings`` mock), in which case we accept
that directly. Returns ``None`` if the result is not usable.
"""
if isinstance(result, expected_type):
return result
final = getattr(result, "final_output", None)
if isinstance(final, expected_type):
return final
# Some test mocks return dicts β coerce best-effort via Pydantic.
if isinstance(final, dict):
try:
return expected_type.model_validate(final)
except Exception: # noqa: BLE001
return None
if isinstance(result, dict):
try:
return expected_type.model_validate(result)
except Exception: # noqa: BLE001
return None
return None
def _record_actual_usage_delta(
limiter: TokenRateLimiter,
*,
model: str,
estimate: int,
result: Any,
) -> None:
"""Backfill rate-limit accounting when SDK usage exceeds our estimate.
The Agents SDK shape can vary by version, so this is deliberately
best-effort. If no usage field is discoverable, the original reservation
made before the call still protects the window.
"""
actual = _usage_total_tokens(result)
if actual is None or actual <= estimate:
return
limiter.record(model=model, tokens=actual - estimate)
def _usage_total_tokens(result: Any) -> int | None:
"""Extract total token usage from common OpenAI/Agents SDK result shapes."""
candidates: list[Any] = [result]
raw_responses = getattr(result, "raw_responses", None)
if raw_responses:
candidates.extend(raw_responses)
responses = getattr(result, "responses", None)
if responses:
candidates.extend(responses)
total = 0
found = False
for candidate in candidates:
usage = getattr(candidate, "usage", None)
if usage is None and isinstance(candidate, dict):
usage = candidate.get("usage")
tokens = _tokens_from_usage(usage)
if tokens is not None:
total += tokens
found = True
return total if found else None
def _tokens_from_usage(usage: Any) -> int | None:
if usage is None:
return None
for attr in ("total_tokens", "total_token_count"):
value = getattr(usage, attr, None)
if value is not None:
try:
return int(value)
except (TypeError, ValueError):
pass
if isinstance(usage, dict):
for key in ("total_tokens", "total_token_count"):
value = usage.get(key)
if value is not None:
try:
return int(value)
except (TypeError, ValueError):
pass
input_tokens = getattr(usage, "input_tokens", None)
output_tokens = getattr(usage, "output_tokens", None)
if input_tokens is None and isinstance(usage, dict):
input_tokens = usage.get("input_tokens")
output_tokens = usage.get("output_tokens")
if input_tokens is not None or output_tokens is not None:
try:
return int(input_tokens or 0) + int(output_tokens or 0)
except (TypeError, ValueError):
return None
return None
# ---------------------------------------------------------------------------
# Python fallback merge (used when Lead Auditor agent fails)
# ---------------------------------------------------------------------------
def _python_fallback_merge(
*,
job_id: str,
file_name: str,
slide_count: int,
slide_findings_by_n: dict[int, SlideFindings],
deck_findings: DeckFindings,
) -> FinalAuditResult:
"""Build a :class:`FinalAuditResult` without an LLM merge pass.
Used when the Lead Auditor agent fails or returns nothing. Slide-level
findings retain their slide context; deck-level findings are appended to
slide 1 (a sensible default β they apply across the deck).
"""
slides: list[SlideEnvelopeExtended] = []
for n in range(1, slide_count + 1):
envelope = SlideEnvelopeExtended(slide_number=n, image_url=None, findings=[])
sf = slide_findings_by_n.get(n)
if sf is not None:
for f in sf.findings:
envelope.findings.append(
FindingExtended(
**f.model_dump(),
finding_meta=FindingMeta(source="agent_slide", must_flag=False),
)
)
slides.append(envelope)
if slide_count >= 1:
for f in deck_findings.findings:
slides[0].findings.append(
FindingExtended(
**f.model_dump(),
finding_meta=FindingMeta(source="agent_deck", must_flag=False),
)
)
return FinalAuditResult(
job_id=job_id,
file_name=file_name,
slide_count=slide_count,
summary=SeverityCounts(),
slides=slides,
errors=[],
)
# ---------------------------------------------------------------------------
# Boundary validation + must-flag injection
# ---------------------------------------------------------------------------
def _finalise(
*,
job_id: str,
file_name: str,
slide_count: int,
lead_result: FinalAuditResult,
marker_hits: dict[int, list[Hit]],
ctx: AuditContext,
errors: list[str],
) -> FinalAuditResult:
"""Apply boundary validation, must_flag tagging, and safety-net injection.
Determinism contract
--------------------
Three classes of finding are injected here from pure-Python deterministic
checks, AFTER the LLM has been allowed to add its own subjective findings.
These injectors run unconditionally for every detected violation β they
are NOT gated on whether the LLM also surfaced the same issue. Rationale:
at temperature=1 the LLM stochastically chooses to skip these advisory
inputs, which made repeated runs of the same deck produce wildly different
counts. By emitting one safety_net finding per detected violation we
pin those counts to a deterministic floor (#hits / #failed checks).
The three classes are:
1. text_markers β DRAFT / TW question / Page to be updated
2. confidentiality β present=false OR position_hint != "footer"
3. color_palette β any in_palette=false hex on the slide
Agent findings that overlap a deterministic violation are kept (LLM-side
description / vision evidence may add value), and their finding_meta is
upgraded with must_flag=True for marker overlaps so the dashboard badges
them. Duplicate suppression of the safety_net for marker hits was REMOVED
in the determinism fix β the safety_net always fires per hit.
"""
rubric = ctx.rubric
valid_categories = {rule.category for rule in rubric.rules}
must_flag_meta = rubric.metadata.must_flag_markers
# Normalise the slides list to exactly slide_count entries indexed 1..N.
by_n: dict[int, SlideEnvelopeExtended] = {
env.slide_number: env for env in lead_result.slides
}
normalised: list[SlideEnvelopeExtended] = []
for n in range(1, slide_count + 1):
env = by_n.get(n) or SlideEnvelopeExtended(
slide_number=n, image_url=None, findings=[]
)
# Force slide_number consistency.
env = SlideEnvelopeExtended(
slide_number=n,
image_url=env.image_url,
findings=list(env.findings),
)
normalised.append(env)
# Boundary validation: drop empty-evidence + unknown-category findings.
for env in normalised:
kept: list[FindingExtended] = []
for f in env.findings:
if not f.evidence or not f.evidence.strip():
logger.warning(
"Dropping finding on slide %d: empty evidence (title=%r)",
env.slide_number, f.title,
)
continue
if f.category not in valid_categories:
logger.warning(
"Dropping finding on slide %d: unknown category %r (title=%r)",
env.slide_number, f.category, f.title,
)
continue
kept.append(f)
env.findings = kept
# Tag agent findings whose evidence overlaps a marker hit's context window
# with finding_meta.must_flag = True.
for env in normalised:
hits = marker_hits.get(env.slide_number, [])
if not hits:
continue
for f in env.findings:
if _evidence_overlaps_any_hit(f.evidence, hits):
if not f.finding_meta.must_flag:
f.finding_meta = FindingMeta(
source=f.finding_meta.source, must_flag=True
)
# ---- Determinism floor: ALWAYS inject one safety_net finding per
# detected text_marker hit. Previously this was conditional on the LLM
# not having already surfaced the hit, which created the stochastic
# 48-vs-14-findings regression at temp=1. The duplicate cost is small
# (an extra synthetic finding alongside an LLM-emitted one) and the
# gain is bit-identical counts across runs.
for n, hits in marker_hits.items():
env = normalised[n - 1]
for hit in hits:
inj = _build_safety_net_finding(n, hit, must_flag_meta=must_flag_meta)
env.findings.append(inj)
# ---- Determinism floor: confidentiality_statement.
# Re-run the pure check (cheap) and inject one safety_net finding per
# slide where the rule is violated, regardless of LLM output. The
# canonical_text comes from the rubric β same source the bundle uses.
canonical_conf = _canonical_confidentiality_text(rubric)
if canonical_conf is not None:
conf_rule_id = _confidentiality_rule_id(rubric)
for n in range(1, slide_count + 1):
env = normalised[n - 1]
cc = check_confidentiality_pure(
ctx.parsed_deck, n, canonical_conf
)
if _confidentiality_violates(cc):
env.findings.append(
_build_confidentiality_safety_net_finding(
n, cc, rule_id=conf_rule_id
)
)
# ---- Determinism floor: color_palette.
# Re-collect non-grayscale slide colors and check against the rubric
# palette. One safety_net finding per off-palette hex per slide.
allowed_palette = _allowed_palette_hexes(rubric)
palette_rule_id = _palette_rule_id(rubric)
if allowed_palette:
for n in range(1, slide_count + 1):
env = normalised[n - 1]
offending = _offpalette_hexes_for_slide(
ctx.parsed_deck, n, allowed_palette
)
for hex_str in offending:
env.findings.append(
_build_palette_safety_net_finding(
n, hex_str, rule_id=palette_rule_id
)
)
# Recompute severity summary.
summary = SeverityCounts()
for env in normalised:
for f in env.findings:
if f.severity == "high":
summary.high += 1
elif f.severity == "medium":
summary.medium += 1
elif f.severity == "low":
summary.low += 1
return FinalAuditResult(
job_id=job_id,
file_name=file_name,
slide_count=slide_count,
summary=summary,
slides=normalised,
errors=errors,
)
def _evidence_overlaps_any_hit(evidence: str, hits: list[Hit]) -> bool:
"""True if *evidence* shares text with at least one hit's context window."""
if not evidence:
return False
e_low = evidence.lower()
for hit in hits:
# Direct: the marker term itself appears in the evidence.
if hit.term.lower() in e_low:
return True
# Or: the evidence quotes a chunk of the context window.
cw = hit.context_window.strip().lower()
if cw and cw in e_low:
return True
# Or: the context window contains a meaningful slice of the evidence.
if e_low and len(e_low) >= 12 and e_low in cw:
return True
return False
def _hit_is_covered(hit: Hit, findings: list[FindingExtended]) -> bool:
"""True if any finding's evidence covers the marker term in *hit*."""
needle = hit.term.lower()
cw = hit.context_window.strip().lower()
for f in findings:
ev = f.evidence.lower()
if not ev:
continue
if needle in ev:
return True
if cw and cw in ev:
return True
return False
def _build_safety_net_finding(
slide_n: int, hit: Hit, *, must_flag_meta: dict
) -> FindingExtended:
"""Create a deterministic safety-net Finding for an unmatched marker hit."""
marker_def = must_flag_meta.get(hit.term)
if marker_def is None:
# Fallback: case-insensitive match if the rubric uses a different case.
for k, v in must_flag_meta.items():
if k.lower() == hit.term.lower():
marker_def = v
break
if marker_def is None:
# Last-ditch defaults β keeps the must-flag bar even with rubric drift.
category = "writing_style"
severity = "high"
title_template = f"Visible internal marker: {hit.term}"
rule_id = "writing_style.no_internal_comments"
else:
category = marker_def.category
severity = marker_def.severity_default
title_template = marker_def.title_template
rule_id = marker_def.rule_id
title = f"{title_template} (slide {slide_n})"
description = (
f"Slide {slide_n} contains the must-flag marker {hit.term!r} in "
f"{hit.source} content. Internal markers must be removed before the "
f"deck is sent to a client."
)
evidence = hit.context_window.strip() or hit.term
suggested_fix = (
f"Remove the {hit.term!r} text from slide {slide_n} and verify the "
f"surrounding content reads cleanly without it."
)
return FindingExtended(
category=category,
severity=severity, # type: ignore[arg-type] # validated by Pydantic
confidence=1.0,
title=title,
description=description,
evidence=evidence,
suggested_fix=suggested_fix,
guideline_reference=rule_id,
finding_meta=FindingMeta(source="safety_net", must_flag=True),
)
# ---------------------------------------------------------------------------
# Confidentiality + palette deterministic helpers (mirror slide_bundle logic)
# ---------------------------------------------------------------------------
def _canonical_confidentiality_text(rubric: Any) -> str | None:
"""Return the canonical confidentiality text from the rubric (or None).
Mirrors ``slide_bundle._canonical_confidentiality_text`` so ``_finalise``
can run the deterministic check without importing the bundle module
(which would import the Agents SDK transitively).
"""
for rule in rubric.rules:
if (
rule.category == "confidentiality_statement"
and rule.metadata
and rule.metadata.canonical_text
):
return rule.metadata.canonical_text
return None
def _confidentiality_rule_id(rubric: Any) -> str:
"""Return the rule_id for the confidentiality rule (best-effort)."""
for rule in rubric.rules:
if rule.category == "confidentiality_statement":
return rule.id
return "confidentiality_statement.present_and_positioned"
def _allowed_palette_hexes(rubric: Any) -> list[str]:
"""Return the allowed-hex list for color_palette (uppercase, no '#')."""
for rule in rubric.rules:
if (
rule.category == "color_palette"
and rule.metadata
and rule.metadata.allowed_hex
):
return [h.lstrip("#").upper() for h in rule.metadata.allowed_hex]
return []
def _palette_rule_id(rubric: Any) -> str:
"""Return the rule_id for the color_palette rule (best-effort)."""
for rule in rubric.rules:
if rule.category == "color_palette":
return rule.id
return "color_palette.approved_colors_only"
def _confidentiality_violates(cc: ConfidentialityCheck) -> bool:
"""True iff the confidentiality check should produce a high-severity finding.
Violations:
* statement absent entirely (``present == false``), OR
* statement present but mispositioned (``position_hint != 'footer'``).
The rubric is explicit: footer is the only acceptable position. Header /
body are violations even when the text matches verbatim.
"""
if not cc.present:
return True
if cc.position_hint != "footer":
return True
return False
def _build_confidentiality_safety_net_finding(
slide_n: int,
cc: ConfidentialityCheck,
*,
rule_id: str,
) -> FindingExtended:
"""Synthesize a deterministic ``confidentiality_statement`` finding.
Always severity=high (the rubric default for this rule). The evidence
string is non-empty by construction so the boundary validator keeps it.
"""
if not cc.present:
title = f"Add confidentiality statement (slide {slide_n})"
description = (
f"Slide {slide_n} is missing the canonical confidentiality "
f"statement. The brand rubric requires it on every slide in "
f"Calibri Body 8pt at the master footer position."
)
evidence = (
f"No shape on slide {slide_n} contains the canonical "
f"confidentiality text."
)
suggested_fix = (
"Insert the canonical confidentiality statement in the master "
"footer position with Calibri Body 8pt formatting."
)
else:
title = (
f"Move confidentiality statement to footer (slide {slide_n})"
)
description = (
f"Slide {slide_n} contains the confidentiality statement but it "
f"appears in the {cc.position_hint!r} region. The rubric "
f"requires footer placement (mid-Y β₯ 0.80)."
)
excerpt = (cc.matched_excerpt or "").strip()
evidence = (
f"Confidentiality statement found at {cc.position_hint!r} "
f"position"
+ (f" (shape {cc.matching_shape_id})" if cc.matching_shape_id else "")
+ (f": {excerpt!r}" if excerpt else "")
)
suggested_fix = (
"Reposition the confidentiality statement to the master footer "
f"slot on slide {slide_n}."
)
return FindingExtended(
category="confidentiality_statement",
severity="high", # type: ignore[arg-type]
confidence=1.0,
title=title,
description=description,
evidence=evidence,
suggested_fix=suggested_fix,
guideline_reference=rule_id,
finding_meta=FindingMeta(source="safety_net", must_flag=False),
)
def _is_grayscale_hex(hex_norm: str) -> bool:
"""True if RRGGBB has R==G==B (pure grayscale)."""
if len(hex_norm) != 6:
return False
try:
r, g, b = (
int(hex_norm[0:2], 16),
int(hex_norm[2:4], 16),
int(hex_norm[4:6], 16),
)
except ValueError:
return False
return r == g == b
def _offpalette_hexes_for_slide(
deck: Any, slide_n: int, allowed: list[str]
) -> list[str]:
"""Return de-duped, stable-ordered off-palette hex strings on the slide.
Mirrors ``slide_bundle._collect_slide_hex_colors`` + per-color
``in_palette`` check. The output is the set of run-color hexes that
(a) appear on the slide, (b) are non-grayscale, and (c) are not in the
allowed palette. Ordering is first-seen β important for determinism so
repeat runs yield the same finding ordering.
"""
if slide_n < 1 or slide_n > deck.slide_count:
return []
allowed_set = {a.upper() for a in allowed}
seen: list[str] = []
seen_set: set[str] = set()
slide = deck.slides[slide_n - 1]
for sh in slide.shapes:
for run in sh.runs:
if run.color_rgb is None:
continue
norm = run.color_rgb.lstrip("#").upper()
if not norm or len(norm) != 6:
continue
if _is_grayscale_hex(norm):
continue
if norm in seen_set:
continue
if norm in allowed_set:
continue
seen_set.add(norm)
seen.append(norm)
return seen
def _build_palette_safety_net_finding(
slide_n: int, hex_norm: str, *, rule_id: str
) -> FindingExtended:
"""Synthesize a deterministic ``color_palette`` finding for one off-palette hex."""
pretty = f"#{hex_norm.upper()}"
title = f"Off-palette color {pretty} (slide {slide_n})"
description = (
f"Slide {slide_n} uses {pretty}, which is not in the approved "
f"Farient brand palette. Replace it with the closest approved hex."
)
evidence = f"Run color {pretty} detected in slide {slide_n} text shapes."
suggested_fix = (
f"Replace {pretty} with a brand-approved palette color on slide "
f"{slide_n}."
)
return FindingExtended(
category="color_palette",
severity="medium", # type: ignore[arg-type]
confidence=1.0,
title=title,
description=description,
evidence=evidence,
suggested_fix=suggested_fix,
guideline_reference=rule_id,
finding_meta=FindingMeta(source="safety_net", must_flag=False),
)
# ---------------------------------------------------------------------------
# Public exports for tests
# ---------------------------------------------------------------------------
__all__ = [
"MUST_FLAG_TERMS",
"MAX_CONCURRENT_SLIDES",
"MAX_RETRY_ATTEMPTS",
"SlideBriefing",
"ConsistencyBriefing",
"MergeInput",
"_run_with_retry",
"_is_retriable",
"_retry_after_hint",
"_build_safety_net_finding",
"_build_confidentiality_safety_net_finding",
"_build_palette_safety_net_finding",
"_confidentiality_violates",
"_offpalette_hexes_for_slide",
"_finalise",
"_max_severity",
"_python_fallback_merge",
"run_audit",
]
|