← back to invincible-jha__aumai-transparency

Function bodies 14 total

All specs Real LLM only Function bodies
trail_command function · python · L45-L62 (18 LOC)
src/aumai_transparency/cli.py
def trail_command(
    agent_id: str,
    store_path: str,
    output_fmt: str,
    output_path: str | None,
) -> None:
    """Print or save the audit trail for a specific agent."""
    logger = AuditLogger()
    _load_store(logger, store_path)

    trail = logger.get_trail(agent_id)
    exported = logger.export_trail(trail, fmt=output_fmt)

    if output_path:
        Path(output_path).write_text(exported, encoding="utf-8")
        click.echo(f"Trail written to {output_path}")
    else:
        click.echo(exported)
explain_command function · python · L73-L84 (12 LOC)
src/aumai_transparency/cli.py
def explain_command(trail_path: str) -> None:
    """Generate a human-readable explanation from a trail JSON file."""
    data = json.loads(Path(trail_path).read_text())
    trail = AuditTrail.model_validate(data)
    generator = ExplanationGenerator()
    explanation = generator.explain_decision(trail.events)
    summary = generator.summarize_trail(trail)

    click.echo("=== Explanation ===")
    click.echo(explanation.human_readable)
    click.echo(f"\nConfidence: {explanation.confidence:.2f}")
    click.echo(f"\nSummary:\n{summary}")
log_command function · python · L94-L121 (28 LOC)
src/aumai_transparency/cli.py
def log_command(
    agent_id: str,
    action: str,
    input_json: str,
    output_json: str,
    reasoning: str,
    store_path: str,
) -> None:
    """Manually append an audit event to the store."""
    logger = AuditLogger()
    _load_store(logger, store_path)

    try:
        input_data = json.loads(input_json)
        output_data = json.loads(output_json)
    except json.JSONDecodeError as exc:
        click.echo(f"Error: invalid JSON — {exc}", err=True)
        sys.exit(1)

    event = logger.log_event(
        agent_id=agent_id,
        action=action,
        input_data=input_data,
        output_data=output_data,
        reasoning=reasoning,
    )
    _save_store(logger, store_path)
    click.echo(f"Logged event {event.event_id} for agent {agent_id!r}.")
_load_store function · python · L129-L135 (7 LOC)
src/aumai_transparency/cli.py
def _load_store(logger: AuditLogger, path: str) -> None:
    """Load events from a JSON file into *logger*."""
    p = Path(path)
    if not p.exists():
        return
    raw: dict[str, list[dict[str, object]]] = json.loads(p.read_text())
    logger.load_events(raw)  # type: ignore[arg-type]
AuditLogger.log_event method · python · L31-L57 (27 LOC)
src/aumai_transparency/core.py
    def log_event(
        self,
        agent_id: str,
        action: str,
        input_data: dict[str, Any],
        output_data: dict[str, Any],
        reasoning: str,
        metadata: dict[str, Any] | None = None,
    ) -> AuditEvent:
        """
        Record a new audit event.

        *input_data* and *output_data* are summarized to a capped-length
        string to keep the log lightweight while preserving key details.
        """
        event = AuditEvent(
            event_id=str(uuid.uuid4()),
            agent_id=agent_id,
            action=action,
            input_summary=_summarize(input_data),
            output_summary=_summarize(output_data),
            reasoning=reasoning,
            timestamp=datetime.now(tz=timezone.utc),
            metadata=metadata or {},
        )
        self._events.setdefault(agent_id, []).append(event)
        return event
AuditLogger.get_trail method · python · L59-L70 (12 LOC)
src/aumai_transparency/core.py
    def get_trail(self, agent_id: str) -> AuditTrail:
        """Return an AuditTrail for *agent_id* (empty trail if none logged)."""
        events = list(self._events.get(agent_id, []))
        start = events[0].timestamp if events else datetime.now(tz=timezone.utc)
        end = events[-1].timestamp if events else None
        return AuditTrail(
            trail_id=str(uuid.uuid4()),
            events=events,
            agent_id=agent_id,
            start_time=start,
            end_time=end,
        )
AuditLogger.dump_events method · python · L76-L81 (6 LOC)
src/aumai_transparency/core.py
    def dump_events(self) -> dict[str, list[dict[str, Any]]]:
        """Serialize all events to a plain dict (for persistence)."""
        return {
            agent_id: [e.model_dump(mode="json") for e in events]
            for agent_id, events in self._events.items()
        }
Same scanner, your repo: https://repobility.com — Repobility
AuditLogger.load_events method · python · L83-L88 (6 LOC)
src/aumai_transparency/core.py
    def load_events(self, data: dict[str, list[dict[str, Any]]]) -> None:
        """Restore events from a serialized dict."""
        for agent_id, event_list in data.items():
            for evt in event_list:
                event = AuditEvent.model_validate(evt)
                self._events.setdefault(agent_id, []).append(event)
AuditLogger.export_trail method · python · L90-L101 (12 LOC)
src/aumai_transparency/core.py
    def export_trail(self, trail: AuditTrail, fmt: str = "json") -> str:
        """
        Serialize an AuditTrail.

        *fmt* may be ``"json"`` (default) or ``"text"`` for a human-
        readable audit log.
        """
        if fmt == "json":
            return trail.model_dump_json(indent=2)
        if fmt == "text":
            return _trail_to_text(trail)
        raise ValueError(f"Unsupported export format {fmt!r}. Use 'json' or 'text'.")
ExplanationGenerator.explain_decision method · python · L107-L144 (38 LOC)
src/aumai_transparency/core.py
    def explain_decision(self, events: list[AuditEvent]) -> Explanation:
        """
        Build an Explanation from a list of audit events.

        The 'decision' is taken from the last event's action.  Factors are
        unique actions seen across all events.  Confidence decays slightly
        for longer chains (more complex reasoning paths).
        """
        if not events:
            return Explanation(
                decision="No events to explain.",
                factors=[],
                confidence=0.0,
                human_readable="No audit events were provided.",
            )

        last = events[-1]
        decision = f"{last.action}: {last.output_summary}"
        factors: list[str] = []
        seen: set[str] = set()
        for event in events:
            if event.action not in seen:
                factors.append(
                    f"Step {event.action!r}: {event.reasoning or event.input_summary}"
                )
                seen.add(event.actio
ExplanationGenerator.summarize_trail method · python · L146-L174 (29 LOC)
src/aumai_transparency/core.py
    def summarize_trail(self, trail: AuditTrail) -> str:
        """Return a concise paragraph summarising an entire AuditTrail."""
        events = trail.events
        if not events:
            return f"Agent {trail.agent_id!r} has no recorded events."

        duration_desc = ""
        if trail.end_time:
            delta = (trail.end_time - trail.start_time).total_seconds()
            duration_desc = f" over {delta:.1f}s"

        action_counts: dict[str, int] = {}
        for e in events:
            action_counts[e.action] = action_counts.get(e.action, 0) + 1

        top_actions = sorted(
            action_counts.items(), key=lambda kv: kv[1], reverse=True
        )[:3]
        top_str = ", ".join(
            f"{action!r} ({count}x)" for action, count in top_actions
        )

        return (
            f"Agent {trail.agent_id!r} performed {len(events)} action(s)"
            f"{duration_desc}. "
            f"Most frequent actions: {top_str}. "
            f"Trail starte
_summarize function · python · L182-L190 (9 LOC)
src/aumai_transparency/core.py
def _summarize(data: dict[str, Any], max_len: int = 200) -> str:
    """Produce a compact JSON summary of *data* capped to *max_len* chars."""
    try:
        raw = json.dumps(data, default=str)
    except (TypeError, ValueError):
        raw = str(data)
    if len(raw) > max_len:
        return raw[: max_len - 3] + "..."
    return raw
_trail_to_text function · python · L193-L215 (23 LOC)
src/aumai_transparency/core.py
def _trail_to_text(trail: AuditTrail) -> str:
    """Render an AuditTrail as a human-readable text document."""
    lines: list[str] = [
        f"AUDIT TRAIL — Agent: {trail.agent_id}",
        f"Trail ID  : {trail.trail_id}",
        f"Start     : {trail.start_time.isoformat()}",
        f"End       : {trail.end_time.isoformat() if trail.end_time else 'ongoing'}",
        f"Events    : {len(trail.events)}",
        "-" * 60,
    ]
    for idx, event in enumerate(trail.events, start=1):
        lines.extend(
            [
                f"\n[{idx}] {event.timestamp.isoformat()}  {event.action}",
                f"  Event ID  : {event.event_id}",
                f"  Input     : {event.input_summary}",
                f"  Output    : {event.output_summary}",
                f"  Reasoning : {event.reasoning or '(none)'}",
            ]
        )
        if event.metadata:
            lines.append(f"  Metadata  : {json.dumps(event.metadata)}")
    return "\n".join(lines)
_build_explanation_text function · python · L218-L240 (23 LOC)
src/aumai_transparency/core.py
def _build_explanation_text(
    events: list[AuditEvent],
    decision: str,
    factors: list[str],
) -> str:
    """Build a natural-language explanation paragraph."""
    intro = f"The agent reached the following decision: {decision}"
    factor_block = "\n".join(f"  - {f}" for f in factors)
    body = textwrap.dedent(
        f"""
        {intro}

        This decision was informed by {len(events)} step(s):
        {factor_block}

        The chain of reasoning began with:
          {events[0].reasoning or events[0].input_summary}

        And concluded with:
          {events[-1].reasoning or events[-1].output_summary}
        """
    ).strip()
    return body