Skip to content

API Reference parrot.tools.infographic_toolkit

github-actions[bot] edited this page Dec 2, 2026 · 4 revisions

parrot.tools.infographic_toolkit

View source

InfographicToolkit — Frozen multi-dataset HTML infographic artifacts (FEAT-197).

This toolkit exposes four tools to the LLM:

infographic_render            — Validate + render + persist.
infographic_list_templates    — Discover available templates.
infographic_get_template_contract — Fetch a template's positional contract.
infographic_validate_blocks   — Dry-run block validation (no persistence).

With return_direct=True the toolkit bypasses LLM re-summarisation: the result of infographic_render is the final agent output, consumed by PandasAgent.ask()'s post-loop branch (TASK-1326).

Dual-emit by default (FEAT-527): every render additionally builds a validated A2UI CreateSurface envelope alongside the HTML artifact — the HTML lane is a permanent sibling emission, not a deprecated path. Set emit_a2ui=False to opt back into HTML-only rendering.

Alias AbstractRecipeStore

Re-exported from parrot.outputs.a2ui.recipes.store.AbstractRecipeStore.

Alias AbstractToolkit

Re-exported from parrot.tools.toolkit.AbstractToolkit.

Alias Artifact

Re-exported from parrot.storage.models.Artifact.

Alias ArtifactCreator

Re-exported from parrot.storage.models.ArtifactCreator.

Alias ArtifactStore

Re-exported from parrot.storage.artifacts.ArtifactStore.

Alias ArtifactType

Re-exported from parrot.storage.models.ArtifactType.

Alias BlockSpec

Re-exported from parrot.models.infographic_templates.BlockSpec.

Alias FreezeProvenanceError

Re-exported from parrot.tools.infographic_recipes.freeze.FreezeProvenanceError.

Alias FreezeValidationError

Re-exported from parrot.tools.infographic_recipes.freeze.FreezeValidationError.

Alias InfographicBlock

Re-exported from parrot.models.infographic.InfographicBlock.

Class InfographicRenderResult

Envelope returned by InfographicToolkit.render (return_direct=True).

Consumed by PandasAgent.ask()'s post-loop branch via isinstance check.

Fields:

Field Type Default Description
artifact_id str
html_url str
html_inline Optional[str] None
template_name str
theme Optional[str] None
data_variables List[str]
enhanced bool False
a2ui_envelope Optional[Dict[str, Any]] None

Alias InfographicResponse

Re-exported from parrot.models.infographic.InfographicResponse.

Alias InfographicTemplate

Re-exported from parrot.models.infographic_templates.InfographicTemplate.

Class InfographicToolkit

Toolkit that produces frozen, multi-dataset HTML infographic artifacts.

Usage::

toolkit = InfographicToolkit(artifact_store=store)
tools = toolkit.get_tools()
# Attach to a PandasAgent before calling ask().
toolkit._bot = pandas_agent

Tools exposed (prefixed with infographic_)::

infographic_render            — typed blocks + pandas (PandasAgent).
infographic_render_template   — trusted HTML+Jinja template + data (ANY agent).
infographic_list_templates
infographic_get_template_contract
infographic_validate_blocks

Recipe tools (Module 6, FEAT-324 — spec G2/G6) are exposed ONLY when recipe_store is configured at construction time; otherwise they are absent from get_tools() entirely (see exclude_tools)::

infographic_save_recipe        — freeze the current session envelope
infographic_list_recipes       — lightweight recipe summaries
infographic_run_recipe         — deterministic replay (no LLM)
infographic_get_recipe_contract — datasets/columns/params a recipe needs
Parameter Type Default Description
artifact_store ArtifactStore Initialised ArtifactStore instance.
template_dirs Optional[Any] None Optional directory (or list of directories) of trusted HTML+Jinja templates consumed by render_template. Passed straight to :class:~parrot.template.engine.TemplateEngine.
templates Optional[Dict[str, str]] None Optional mapping of {name: source} in-memory HTML+Jinja templates for render_template (registered via the engine's DictLoader). Combine with template_dirs or use alone.
emit_a2ui bool True When True (the default — FEAT-527), the render tools additionally produce a validated A2UI CreateSurface envelope (FEAT-273 Module 11, D1a lane) alongside the HTML artifact. The HTML lane is a permanent sibling emission; set to False to opt back into HTML-only rendering.
recipe_store Optional[AbstractRecipeStore] None Optional AbstractRecipeStore (FEAT-324, Module 4/6). When provided, the four recipe tools (infographic_save_recipe, infographic_list_recipes, infographic_run_recipe, infographic_get_recipe_contract) are exposed; otherwise they are excluded from get_tools() entirely.
recipe_runner Optional[RecipeRunner] None Optional pre-built RecipeRunner. Takes precedence over dataset_manager (below) if both are given.
dataset_manager Optional[Any] None Optional DatasetManager used to build a RecipeRunner when recipe_runner is not supplied directly (a RecipeRunner needs both a store and a dataset manager — see parrot.tools.infographic_recipes.runner.RecipeRunner).
**kwargs {} Forwarded to AbstractToolkit.__init__.

Attributes:

Attribute Type Description
tool_prefix Optional[str]
prefix_separator str
exclude_tools Tuple[str, ...]
return_direct bool

Method InfographicToolkit.add_template

Register a trusted in-memory HTML+Jinja template for render_template.

Sync helper (not exposed as an LLM tool). Lets an agent register templates after construction. Templates are trusted — never pass untrusted/LLM-authored Jinja source here (no sandbox is applied).

add_template(name: str, source: str) -> None

Parameter Type Default Description
name str Template name referenced by render_template(template_name=...).
source str HTML+Jinja template source.

Method InfographicToolkit.get_tools

Return the generated tools, ensuring return_direct is propagated.

get_tools(**kwargs)

Parameter Type Default Description
**kwargs {}

Method InfographicToolkit.set_bot

Bind this toolkit to a bot instance for enhance-mode support.

Binding also teaches the bot how to drive the infographic tools: the INFOGRAPHIC_SYSTEM_PROMPT_ADDON guidance is appended to the bot's system_prompt_template so any agent that registers this toolkit can produce infographics ad-hoc — no per-report skill required. Call this during the agent's configure() (before super().configure() runs _define_prompt()) so the guidance lands in the finalised prompt.

set_bot(bot: Any) -> None

Parameter Type Default Description
bot Any Bot instance that must implement _get_repl_locals() -> Dict[str, Any] and optionally enhance_infographic(...). The bot is stored as self._bot and accessed by _maybe_enhance and _get_repl_locals.

Method InfographicToolkit.render

Validate, render, and persist an infographic artifact.

This is the primary tool. The LLM calls it as the last tool in the turn after computing all required DataFrames.

The result (InfographicRenderResult) is returned verbatim to the caller — do NOT summarise it.

render(template_name: str, theme: Optional[str], mode: Literal['deterministic', 'enhance'], data_variables: List[str], blocks: Optional[List[Dict[str, Any]]] = None, blocks_variable: Optional[str] = None, enhance_brief: Optional[str] = None) -> InfographicRenderResult

Parameter Type Default Description
template_name str Template identifier from infographic_list_templates.
theme Optional[str] Theme name (e.g. "dark", "light"). Pass null to use the template's default_theme.
mode Literal['deterministic', 'enhance'] "deterministic" for skeleton-only; "enhance" for optional JS interactivity (requires enhance_brief).
data_variables List[str] Names of DataFrames in the pandas REPL locals that provide the underlying data for this infographic.
blocks Optional[List[Dict[str, Any]]] None List of block dicts matching the template's positional contract. Use infographic_get_template_contract to see the expected types and counts. Prefer blocks_variable for anything but a tiny, hand-written block list.
blocks_variable Optional[str] None Preferred. Name of a Python variable in the pandas REPL that holds the block list (e.g. "fp_blocks" built by a skill's compute.py). The toolkit reads the blocks straight from the REPL namespace, so you never have to copy a large JSON payload into the tool call. Takes precedence over blocks when both are given.
enhance_brief Optional[str] None Brief description of the desired interactivity (required when mode == "enhance"; ignored otherwise).

Returns: InfographicRenderResult — InfographicRenderResult with artifact_id, html_url, optional html_inline, and provenance fields.

Raises:

  • InfographicValidationError — When any validation check fails. The code and detail fields identify the problem.

Method InfographicToolkit.render_template

Render a pre-registered HTML+Jinja template into an infographic artifact.

Use this when you already have the answer data (a dict, or the text/JSON produced by a previous step) plus a named HTML+Jinja template registered on this toolkit. Unlike infographic_render (typed blocks computed from DataFrames in a pandas REPL), this path fills a trusted template directly, so it works for any agent — no pandas namespace required.

Call it as the LAST tool in the turn. The result is returned verbatim — do NOT summarise it or paste the HTML/envelope into your answer.

render_template(template_name: str, data: Optional[Dict[str, Any]] = None, theme: Optional[str] = None, title: Optional[str] = None) -> InfographicRenderResult

Parameter Type Default Description
template_name str Name of a template registered via template_dirs, templates= or add_template().
data Optional[Dict[str, Any]] None Authoritative, JSON-serialisable payload exposed to the template as data (e.g. {{ data.title }}). This is the reliable channel — prefer it over the best-effort message context.
theme Optional[str] None Optional theme name, exposed as theme and stored on the artifact definition.
title Optional[str] None Optional artifact title (defaults to Infographic — <name>).

Returns: InfographicRenderResult — InfographicRenderResult with artifact_id, html_url and optional html_inline (populated only when the HTML is < 50 KB).

Raises:

  • InfographicValidationError — TEMPLATE_ENGINE_UNSET when no template source is configured; TEMPLATE_UNKNOWN when template_name is not found; TEMPLATE_RENDER_ERROR on any Jinja error (e.g. a missing variable under StrictUndefined).

Method InfographicToolkit.render_data_template

Render a self-contained HTML template by splicing a JSON payload.

Unlike infographic_render_template (Jinja), this data-splice mode targets a self-contained HTML dashboard whose client-side JS reads its data from a <script type="application/json" id="..."> marker tag (FEAT-326, generalizing the standalone budget-variance report script). The registered template source is loaded raw (never Jinja-rendered), the payload is JSON-serialised and injected between the marker's open/close tags, and the result is otherwise byte-identical to the template. The artifact is persisted exactly like render_template.

Call it as the LAST tool in the turn. The result is returned verbatim — do NOT summarise it or paste the HTML/envelope into your answer.

render_data_template(template_name: str, payload: Dict[str, Any], descriptor: Optional['SectionDescriptor'] = None, marker_id: str = 'report-data', title: Optional[str] = None) -> InfographicRenderResult

Parameter Type Default Description
template_name str Name of a template registered via template_dirs, templates= or add_template().
payload Dict[str, Any] JSON-serialisable data injected into the marker script tag. numpy/pandas scalars are coerced; NaN/Infinity are rejected loudly (they would otherwise produce invalid JSON).
descriptor Optional['SectionDescriptor'] None Optional :class:SectionDescriptor. When supplied, its payload-shape validation gate runs BEFORE any splice/persist, and its splice_marker_id overrides marker_id.
marker_id str 'report-data' HTML id of the <script type="application/json"> marker. Ignored when descriptor is supplied.
title Optional[str] None Optional artifact title (defaults to Infographic — <name>).

Returns: InfographicRenderResult — InfographicRenderResult with artifact_id, html_url and optional html_inline (populated only when the HTML is small).

Raises:

  • InfographicValidationError — TEMPLATE_ENGINE_UNSET when no template source is configured; TEMPLATE_UNKNOWN when template_name is not found; SPLICE_MARKER_MISSING when the marker (or its closing tag) is absent; PAYLOAD_NOT_SERIALIZABLE when the payload contains NaN/Infinity or a non-coercible value; payload_shape_mismatch when a supplied descriptor's gate fails.

Method InfographicToolkit.list_templates

Return the list of available infographic templates.

list_templates() -> List[Dict[str, str]]

Returns: List[Dict[str, str]] — List of dicts with name and description keys.

Method InfographicToolkit.get_template_contract

Return the positional block contract for a template.

Useful before calling infographic_render to ensure the blocks you build match the template's block_specs exactly.

get_template_contract(template_name: str) -> Dict[str, Any]

Parameter Type Default Description
template_name str Template identifier.

Returns: Dict[str, Any] — Dict with name, description, default_theme, block_specs (list with positional index, type, constraints), and js_bundles.

Raises:

  • InfographicValidationError — Code TEMPLATE_UNKNOWN when the template is not found.

Method InfographicToolkit.validate_blocks

Dry-run block validation without rendering or persisting.

This tool NEVER raises — it returns a structured result so the LLM can branch on success/failure. Use this before infographic_render to avoid hard errors.

validate_blocks(template_name: str, blocks: Optional[List[Dict[str, Any]]] = None, blocks_variable: Optional[str] = None) -> Dict[str, Any]

Parameter Type Default Description
template_name str Template identifier.
blocks Optional[List[Dict[str, Any]]] None Block list to validate. Prefer blocks_variable for anything but a tiny, hand-written block list.
blocks_variable Optional[str] None Preferred. Name of a Python variable in the pandas REPL holding the block list (e.g. "fp_blocks"). Validated straight from the REPL namespace — no need to copy JSON into the call. Takes precedence over blocks.

Returns: Dict[str, Any] — {"ok": True} on success; {"ok": False, "code": ..., "detail": ...} on failure.

Method InfographicToolkit.build_block

Build ONE infographic block from REPL data and append it to a list.

This is the reliable way to assemble chart/table blocks: instead of hand-writing large JSON arrays into the tool call (the main failure mode), point this tool at a DataFrame already in the pandas namespace. It reads the frame, constructs the block, validates it against the block schema, and appends it to an accumulator list variable (into, default "infographic_blocks") IN CALL ORDER. Build every block in the template's positional order, then render with infographic_render(blocks_variable=into, ...).

Block sources by type:

  • "chart" — derived from data_variable. label_column becomes the x-axis/category labels; each name in value_columns becomes one series. chart_type (bar/line/pie/…), title and layout ("full"/"half") are optional.
  • "table" — derived from data_variable. table_columns selects and orders columns (defaults to all); rows come from the frame.
  • any other type (title/hero_card/summary/callout/…) — carries no DataFrame: pass the literal block dict via block.

max_rows caps how many rows are read (chart/table) to keep the artifact lean. NumPy/pandas scalars and Timestamps are coerced to native JSON types automatically.

build_block(block_type: str, into: str = 'infographic_blocks', data_variable: Optional[str] = None, chart_type: Optional[str] = None, label_column: Optional[str] = None, value_columns: Optional[List[str]] = None, table_columns: Optional[List[str]] = None, max_rows: Optional[int] = None, title: Optional[str] = None, layout: Optional[str] = None, block: Optional[Dict[str, Any]] = None) -> Dict[str, Any]

Parameter Type Default Description
block_type str The block type to build.
into str 'infographic_blocks' Accumulator list variable name in the pandas REPL. Created if absent; subsequent calls append in order.
data_variable Optional[str] None DataFrame name in the REPL (required for chart/table).
chart_type Optional[str] None Chart kind for block_type="chart".
label_column Optional[str] None Column used as chart labels (chart only).
value_columns Optional[List[str]] None Columns used as chart series — one series each (chart).
table_columns Optional[List[str]] None Columns to include/order (table only; default all).
max_rows Optional[int] None Optional cap on rows read from the DataFrame.
title Optional[str] None Optional block title (chart/table).
layout Optional[str] None Optional "full"/"half" layout hint (chart).
block Optional[Dict[str, Any]] None Literal block dict for non chart/table types (must carry "type").

Returns: Dict[str, Any] — {"ok": True, "into": <name>, "index": <pos>, "block_type": <type>, "n_blocks": <len>} on success; {"ok": False, "code": ..., "detail": ...} on a structured failure.

Method InfographicToolkit.infographic_save_recipe

Freeze the current session's infographic construction into a replayable recipe.

Call this AFTER building an infographic in this session, once you know EXACTLY which registered datasets and registered transformer calls produced its data. Freezing captures those as recipe steps so the same infographic can be regenerated later with fresh data, deterministically, with no LLM in the loop (spec G2/G3).

Every dataset referenced in dataset_names must be a name registered with the DatasetManager, and every step in transform_steps must name a REGISTERED @infographic_transformer — ad-hoc pandas computation done directly in this session cannot be frozen (this is a deliberate boundary, not a limitation to work around).

infographic_save_recipe(name: str, title: str, layout_component: str, layout_properties: Dict[str, Any], dataset_names: Dict[str, str], transform_steps: List[Dict[str, Any]], description: Optional[str] = None, render_profile: str = 'interactive-html', theme: Optional[str] = None) -> Dict[str, Any]

Parameter Type Default Description
name str Unique recipe name (its storage key).
title str Human-readable recipe title.
layout_component str Catalog component name for the layout (e.g. "Infographic", "Chart").
layout_properties Dict[str, Any] Catalog properties for the layout (A2UI v1.0, top-level, no properties wrapper); data-carrying properties use {"path": "/pointer"} bindings into the dataModel produced by transform_steps.
dataset_names Dict[str, str] Mapping of data-source alias -> registered DatasetManager dataset name, e.g. {"snapshots": "budget_ledger"}.
transform_steps List[Dict[str, Any]] Ordered list of transform-step dicts, each shaped like {"transformer": "division_breakdown", "inputs": ["snapshots"], "params": {}, "output_key": "division_breakdown"}.
description Optional[str] None Optional longer description.
render_profile str 'interactive-html' Renderer profile name for replay (default "interactive-html").
theme Optional[str] None Optional theme name.

Returns: Dict[str, Any] — {"status": "ok", "recipe": {...summary...}} on success, or {"status": "error", "detail": ...} / {"status": "error", "errors": [...]} when the provenance is inexpressible or the normalized recipe fails dry-run validation.

Method InfographicToolkit.infographic_list_recipes

List saved recipes available to the current user (lightweight summaries).

Use this to discover recipe names before calling infographic_run_recipe or infographic_get_recipe_contract.

infographic_list_recipes() -> List[Dict[str, Any]]

Returns: List[Dict[str, Any]] — List of dicts with name, title, description, owner, updated_at — never full recipe definitions.

Method InfographicToolkit.infographic_run_recipe

Replay a saved recipe deterministically (no LLM) and render a fresh artifact.

Re-fetches the recipe's datasets, re-runs its registered transform chain, and renders a new artifact — same construction instructions, fresh data (spec G3).

infographic_run_recipe(name: str, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]

Parameter Type Default Description
name str Recipe name to run.
params Optional[Dict[str, Any]] None Optional override values for the recipe's declared params (e.g. {"month": "2026-06"}); undeclared names are rejected.

Returns: Dict[str, Any] — {"status": "ok", "artifact_id": ..., "mime_type": ..., "title": ..., "filename": ...} on success. On failure: {"status": "error", "error": {...RecipeRunError fields...}} — a structured diagnostic (recipe/stage/transformer/dataset/ missing_columns/detail) for you to explain to the user; never a raw traceback.

Method InfographicToolkit.infographic_get_recipe_contract

Return the datasets, required columns, and params a recipe needs to replay.

Use this before running or scheduling a recipe to verify it is still replayable (its datasets are registered, its transformers exist).

infographic_get_recipe_contract(name: str) -> Dict[str, Any]

Parameter Type Default Description
name str Recipe name.

Returns: Dict[str, Any] — {"status": "ok", "name": ..., "datasets": [{"alias":..., "dataset":...}], "params": [{"name":...,"default":..., "description":...}], "transforms": [{"transformer":..., "output_key":...,"requires_columns":{...}}]}, or {"status": "error", "detail": ...} if the recipe or store is unavailable.

Class InfographicValidationError

Structured error raised by the validation pipeline.

All errors carry a stable code (for client routing) and a detail dict (for structured logging and user display).

Valid codes::

TEMPLATE_UNKNOWN
SLOT_MISSING
SLOT_TYPE_MISMATCH
SLOT_ITEM_COUNT_INVALID
EXTRA_BLOCKS
DATA_VAR_MISSING
DATA_VAR_EMPTY
THEME_INVALID
ENHANCE_OUTPUT_INVALID
TEMPLATE_ENGINE_UNSET    # render_template: no templates configured
TEMPLATE_RENDER_ERROR    # render_template: Jinja render failure
Parameter Type Default Description
code str
detail Dict[str, Any]

Alias JSBundle

Re-exported from parrot.models.infographic.JSBundle.

Alias JinjaConfig

Re-exported from parrot.template.engine.JinjaConfig.

Attribute MAX_ENHANCE_ROWS

Type: int

Alias OutputMode

Re-exported from parrot.models.outputs.OutputMode.

Alias RecipeNotFoundError

Re-exported from parrot.outputs.a2ui.recipes.store.RecipeNotFoundError.

Alias RecipeRunException

Re-exported from parrot.tools.infographic_recipes.runner.RecipeRunException.

Alias RecipeRunner

Re-exported from parrot.tools.infographic_recipes.runner.RecipeRunner.

Alias SectionDescriptor

Re-exported from parrot.tools.infographic_sections.SectionDescriptor.

Alias ServerParam

Re-exported from parrot.tools.server_params.ServerParam.

Alias TemplateEngine

Re-exported from parrot.template.engine.TemplateEngine.

Alias build_principal_context

Re-exported from parrot.auth.permission.build_principal_context.

Alias build_public_html_url

Re-exported from parrot.storage.artifact_signing.build_public_html_url.

Alias freeze_session_envelope

Re-exported from parrot.tools.infographic_recipes.freeze.freeze_session_envelope.

Alias get_infographic_html_renderer

Re-exported from parrot.outputs.formats.get_infographic_html_renderer.

Alias infographic_registry

Re-exported from parrot.models.infographic_templates.infographic_registry.

Alias theme_registry

Re-exported from parrot.models.infographic.theme_registry.

Alias transformer_registry

Re-exported from parrot.outputs.a2ui.recipes.transformers.transformer_registry.

Architecture

Clients

Bots & Agents

Memory

Knowledge

Tools & Toolkits

Flows

Experts

Skills

Stores & Loaders

MCP & A2A

Server & APIs

Integrations

Outputs & A2UI

Prompts

Security

Operations

Migration

SDD Tooling

LLM Wiki

Deployment

Decisions

API Reference

Clone this wiki locally