"""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, ]