Spaces:
Sleeping
Sleeping
File size: 13,184 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 | """Agent tools for the Farient brand-compliance review system.
All 9 tools are decorated with ``@function_tool`` so the OpenAI Agents SDK
derives their JSON Schema from the type annotations. Each tool takes a
``RunContextWrapper[AuditContext]`` as its first argument; the SDK injects
this automatically and does NOT include it in the derived schema.
Design pattern
--------------
Each tool is implemented as a plain Python function (``_impl_*``), then
wrapped with ``function_tool(...)`` to produce the SDK ``FunctionTool`` object.
The ``FunctionTool`` object is exported under the canonical tool name (e.g.
``list_slide_summaries``), while the underlying implementation is also directly
callable for unit tests via ``list_slide_summaries_fn`` aliases.
Tests call ``list_slide_summaries_fn(wrapper, ...)`` directly — no LLM, no SDK
machinery required. The SDK uses the ``FunctionTool`` objects when running
agents.
Error contract
--------------
* Tools RAISE on invalid input or missing data. The Agents SDK surfaces
these exceptions back to the agent automatically.
* The sole typed non-raise case: ``get_slide_image`` returns
``RenderUnavailable`` (a TypedDict) when rendering was skipped — the agent
has a meaningful text-only fallback for that specific case.
* Do NOT return ad-hoc ``{"error": "..."}`` shapes — that pollutes the JSON
Schema the SDK derives from the return type.
There is intentionally NO ``record_finding`` tool. The agent's structured
output (``output_type=SlideFindings`` / ``DeckFindings``) is the sole
authoritative finding source.
"""
from __future__ import annotations
import base64
from dataclasses import dataclass
from pathlib import Path
from typing import TypedDict
from agents import RunContextWrapper, function_tool
from agents.tool import ToolOutputImage
from agents.context import AuditContext
from services.confidentiality import ConfidentialityCheck, check_confidentiality_pure
from services.markers import Hit, find_text_markers_pure
# ---------------------------------------------------------------------------
# Return-type models
# ---------------------------------------------------------------------------
@dataclass
class SlideSummary:
"""Brief overview of one slide — avoids dumping full content into context."""
slide_n: int
text_preview: str # first 200 chars of extracted_text
has_notes: bool
has_image: bool # whether a rendered PNG exists for this slide
@dataclass
class ShapeMetadata:
"""Compact shape info for get_slide_text."""
shape_id: str
shape_type: str
name: str
left: int
top: int
width: int
height: int
font_sizes: list[float] # unique non-None font sizes from runs
colors: list[str] # unique non-None RGB hex strings from runs
@dataclass
class SlideText:
"""Full text + structured shape metadata for one slide."""
slide_n: int
extracted_text: str
notes_text: str
shapes: list[ShapeMetadata]
@dataclass
class RubricRule:
"""One rule within a rubric section."""
rule_id: str
rule_text: str
severity_default: str
detection_type: str
examples_do: str | None
examples_dont: str | None
source_ref: str
metadata: dict # raw metadata dict (may include allowed_hex, canonical_text, etc.)
@dataclass
class RubricSection:
"""All rules for one rubric category."""
category: str
rules: list[RubricRule]
class RenderUnavailable(TypedDict):
"""Returned by get_slide_image when rendering was skipped or the slide has no PNG.
The agent recognises ``type == "render_unavailable"`` as a signal to fall
back to text-only analysis.
"""
type: str # always "render_unavailable"
# ---------------------------------------------------------------------------
# Private helpers
# ---------------------------------------------------------------------------
def _slide_image_path(ctx: AuditContext, slide_n: int) -> Path | None:
"""Return the PNG path for *slide_n* (0-indexed in slide_paths), or None."""
idx = slide_n - 1
if ctx.render_result.skipped or ctx.render_result.render_failed:
return None
if idx < 0 or idx >= len(ctx.render_result.slide_paths):
return None
path = ctx.render_result.slide_paths[idx]
if not path.exists():
return None
return path
def _validate_slide_n(ctx: AuditContext, slide_n: int) -> None:
"""Raise ValueError if slide_n is out of range."""
deck = ctx.parsed_deck
if slide_n < 1 or slide_n > deck.slide_count:
raise ValueError(
f"slide_n={slide_n} out of range; deck has {deck.slide_count} slide(s)"
)
# ---------------------------------------------------------------------------
# Raw implementation functions (directly callable, used in unit tests)
# ---------------------------------------------------------------------------
def _impl_list_slide_summaries(
ctx: RunContextWrapper[AuditContext],
) -> list[SlideSummary]:
"""Return a brief summary for every slide: text preview, notes flag, image flag."""
audit = ctx.context
summaries: list[SlideSummary] = []
for slide in audit.parsed_deck.slides:
n = slide.slide_number
summaries.append(
SlideSummary(
slide_n=n,
text_preview=slide.extracted_text[:200],
has_notes=bool(slide.notes_text),
has_image=_slide_image_path(audit, n) is not None,
)
)
return summaries
def _impl_get_slide_text(
ctx: RunContextWrapper[AuditContext],
slide_n: int,
) -> SlideText:
"""Return full text and structured shape metadata (font sizes, colors, EMU positions) for slide_n."""
audit = ctx.context
_validate_slide_n(audit, slide_n)
slide = audit.parsed_deck.slides[slide_n - 1]
shape_metas: list[ShapeMetadata] = []
for sh in slide.shapes:
font_sizes = sorted(
{r.font_size_pt for r in sh.runs if r.font_size_pt is not None}
)
colors = sorted(
{r.color_rgb for r in sh.runs if r.color_rgb is not None}
)
shape_metas.append(
ShapeMetadata(
shape_id=sh.shape_id,
shape_type=sh.shape_type,
name=sh.name,
left=sh.left,
top=sh.top,
width=sh.width,
height=sh.height,
font_sizes=font_sizes,
colors=colors,
)
)
return SlideText(
slide_n=slide_n,
extracted_text=slide.extracted_text,
notes_text=slide.notes_text,
shapes=shape_metas,
)
def _impl_get_slide_notes(
ctx: RunContextWrapper[AuditContext],
slide_n: int,
) -> str | None:
"""Return the speaker notes for slide_n, or None if the slide has no notes."""
audit = ctx.context
_validate_slide_n(audit, slide_n)
notes = audit.parsed_deck.slides[slide_n - 1].notes_text
return notes if notes else None
def _impl_get_slide_image(
ctx: RunContextWrapper[AuditContext],
slide_n: int,
) -> ToolOutputImage | RenderUnavailable:
"""Return the rendered PNG for slide_n as a ToolOutputImage (base64 data URL), or RenderUnavailable if not rendered."""
audit = ctx.context
_validate_slide_n(audit, slide_n)
png_path = _slide_image_path(audit, slide_n)
if png_path is None:
return RenderUnavailable(type="render_unavailable")
png_bytes = png_path.read_bytes()
b64 = base64.b64encode(png_bytes).decode("ascii")
data_url = f"data:image/png;base64,{b64}"
return ToolOutputImage(image_url=data_url)
def _impl_list_rubric_categories(
ctx: RunContextWrapper[AuditContext],
) -> list[str]:
"""Return all rubric category IDs the agent can request via get_rubric_section."""
rubric = ctx.context.rubric
seen: list[str] = []
for rule in rubric.rules:
if rule.category not in seen:
seen.append(rule.category)
return seen
def _impl_get_rubric_section(
ctx: RunContextWrapper[AuditContext],
category: str,
) -> RubricSection:
"""Return all rules for a rubric category (rule_text, examples, severity, source_ref, metadata)."""
rubric = ctx.context.rubric
matching = [r for r in rubric.rules if r.category == category]
if not matching:
valid = sorted({r.category for r in rubric.rules})
raise ValueError(
f"Unknown rubric category: {category!r}. "
f"Valid categories: {valid}"
)
rules: list[RubricRule] = []
for r in matching:
meta: dict = {}
if r.metadata:
if r.metadata.allowed_hex is not None:
meta["allowed_hex"] = r.metadata.allowed_hex
if r.metadata.canonical_text is not None:
meta["canonical_text"] = r.metadata.canonical_text
rules.append(
RubricRule(
rule_id=r.id,
rule_text=r.rule_text,
severity_default=r.severity_default,
detection_type=r.detection_type,
examples_do=r.examples.do if r.examples else None,
examples_dont=r.examples.dont if r.examples else None,
source_ref=r.source_ref,
metadata=meta,
)
)
return RubricSection(category=category, rules=rules)
def _impl_check_palette_color(
ctx: RunContextWrapper[AuditContext],
hex: str,
) -> dict:
"""Check whether a hex color is in the Farient brand palette. Accepts '#006EBE' or '006EBE', case-insensitive."""
rubric = ctx.context.rubric
# Find the color_palette rule with allowed_hex
allowed: list[str] = []
for rule in rubric.rules:
if rule.category == "color_palette" and rule.metadata and rule.metadata.allowed_hex:
allowed = rule.metadata.allowed_hex
break
# Normalise input: strip leading '#', uppercase
normalised = hex.lstrip("#").upper()
# Normalise the palette entries the same way
in_palette = any(entry.lstrip("#").upper() == normalised for entry in allowed)
return {"in_palette": in_palette, "allowed": allowed}
def _impl_find_text_markers(
ctx: RunContextWrapper[AuditContext],
slide_n: int,
markers: list[str],
) -> list[Hit]:
"""Case-insensitive scan of slide_n text + notes for the given marker strings. Returns hits with offsets and context windows."""
return find_text_markers_pure(ctx.context.parsed_deck, slide_n, markers)
def _impl_check_confidentiality_statement(
ctx: RunContextWrapper[AuditContext],
slide_n: int,
) -> ConfidentialityCheck:
"""Check whether slide_n contains the canonical confidentiality statement and return its position hint (header/footer/body/absent)."""
audit = ctx.context
# Find canonical_text from rubric
canonical_text: str | None = None
for rule in audit.rubric.rules:
if (
rule.category == "confidentiality_statement"
and rule.metadata
and rule.metadata.canonical_text
):
canonical_text = rule.metadata.canonical_text
break
if canonical_text is None:
raise ValueError(
"Rubric does not contain a canonical_text for 'confidentiality_statement'"
)
return check_confidentiality_pure(audit.parsed_deck, slide_n, canonical_text)
# ---------------------------------------------------------------------------
# SDK-wrapped FunctionTool objects (registered with @function_tool)
# Each is also aliased to the canonical name for SDK agent registration.
# The _fn aliases give tests a direct Python-callable handle.
# ---------------------------------------------------------------------------
list_slide_summaries = function_tool(_impl_list_slide_summaries)
get_slide_text = function_tool(_impl_get_slide_text)
get_slide_notes = function_tool(_impl_get_slide_notes)
get_slide_image = function_tool(_impl_get_slide_image)
list_rubric_categories = function_tool(_impl_list_rubric_categories)
get_rubric_section = function_tool(_impl_get_rubric_section)
check_palette_color = function_tool(_impl_check_palette_color)
find_text_markers = function_tool(_impl_find_text_markers)
check_confidentiality_statement = function_tool(_impl_check_confidentiality_statement)
# Plain-callable aliases for unit tests (no SDK machinery)
list_slide_summaries_fn = _impl_list_slide_summaries
get_slide_text_fn = _impl_get_slide_text
get_slide_notes_fn = _impl_get_slide_notes
get_slide_image_fn = _impl_get_slide_image
list_rubric_categories_fn = _impl_list_rubric_categories
get_rubric_section_fn = _impl_get_rubric_section
check_palette_color_fn = _impl_check_palette_color
find_text_markers_fn = _impl_find_text_markers
check_confidentiality_statement_fn = _impl_check_confidentiality_statement
# Canonical list of all 9 tools for registration
ALL_TOOLS = [
list_slide_summaries,
get_slide_text,
get_slide_notes,
get_slide_image,
list_rubric_categories,
get_rubric_section,
check_palette_color,
find_text_markers,
check_confidentiality_statement,
]
|