Skip to content

API Reference parrot.tools.dataset_manager.tool

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

parrot.tools.dataset_manager.tool

View source

DatasetManager: A Toolkit and Data Catalog for PandasAgent.

Provides:

  • Dataset catalog with add/remove/activate/deactivate
  • Full metadata/EDA capabilities (replaces MetadataTool)
  • Column type categorization and metrics guide generation
  • Data quality checks (NaN detection, completeness)
  • LLM-exposed tools for discovery, metadata retrieval, and management

Alias AbstractPermissionResolver

Re-exported from parrot.auth.resolver.AbstractPermissionResolver.

Alias AbstractToolkit

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

Alias DataPlanePolicyGuard

Re-exported from parrot.auth.dataplane_guard.DataPlanePolicyGuard.

Alias DataSource

Re-exported from parrot.tools.dataset_manager.sources.base.DataSource.

Class DatasetEntry

Lifecycle wrapper around a DataSource.

Knows WHETHER data is in memory and manages its lifecycle:

  • materialize(**params): fetch from source, cache result in _df
  • evict(): release _df from memory (source reference and schema are retained)

Provides backward-compatible properties (df, query_slug, _column_metadata) so existing DatasetManager methods continue to work without changes.

Computed columns (computed_columns) are applied post-materialization and before type categorization, so they appear as regular columns throughout the DatasetManager API.

Parameter Type Default Description
name str
description Optional[str] None
source Optional[DataSource] None
metadata Optional[Dict[str, Any]] None
is_active bool True
auto_detect_types bool True
cache_ttl int 3600
no_cache bool False
df Optional[pd.DataFrame] None
query_slug Optional[str] None
computed_columns Optional[List[Any]] None
usage_guidance Optional[Dict[str, List[str]]] None
protected bool False

Attributes:

Attribute Type Description
description str
unavailable_reason Optional[str]
usage_guidance Dict[str, List[str]]
loaded bool True if data has been materialized into memory.
shape Tuple[int, int] Shape of the loaded DataFrame, or (0, 0) if not loaded.
columns List[str] Column names. Falls back to source schema (TableSource) when not loaded. In prefetch state (not yet loaded), computed column names are appended after the schema columns so the LLM can see them before materialization.
memory_usage_mb float Memory usage of the loaded DataFrame in MB.
null_count int Total null count across all columns.
column_types Optional[Dict[str, str]] Semantic column types (populated after materialization).
df Optional[pd.DataFrame] Backward-compat: return the loaded DataFrame (same as _df).
query_slug Optional[str] Backward-compat: return slug if source is a QuerySlugSource.

Method DatasetEntry.materialize

Fetch data from source if not already loaded (or if force=True).

Computed columns are applied post-fetch and before type categorization so they appear as regular columns in all metadata surfaces.

materialize(force: bool = False, **params) -> pd.DataFrame

Parameter Type Default Description
force bool False If True, re-fetch even if _df is already populated.
**params {} Passed through to source.fetch() (e.g. sql=, conditions=).

Returns: pd.DataFrame — The loaded DataFrame.

Method DatasetEntry.evict

Release DataFrame from memory.

Source reference and schema (_schema on source, _column_types) are cleared. The source itself is retained so the dataset can be re-materialized later.

evict() -> None

Method DatasetEntry.to_info

Serialize this entry to a DatasetInfo Pydantic model.

Schema (columns + column_types) is populated even when loaded=False, provided the source has prefetched schema (e.g. TableSource).

to_info(alias: Optional[str] = None) -> DatasetInfo

Parameter Type Default Description
alias Optional[str] None Standardized alias string (e.g. 'df1', 'df2').

Returns: DatasetInfo — DatasetInfo instance ready for LLM consumption.

Class DatasetInfo

Schema for dataset information exposed to LLM.

Schema fields (columns, column_types) are available even when the dataset is not yet loaded — for TableSource entries whose schema was prefetched.

Fields:

Field Type Default Description
name str Dataset name/identifier
alias Optional[str] None Standardized alias (df1, df2, etc.)
description str '' Dataset description
source_type Literal['dataframe', 'query_slug', 'sql', 'table', 'airtable', 'smartsheet', 'iceberg', 'mongo', 'deltatable', 'composite'] 'dataframe' Type of data source backing this dataset
source_description str '' Human-readable description from the DataSource (from source.describe())
columns List[str] List of column names
column_types Optional[Dict[str, str]] None Detected column type (integer, float, datetime, categorical_text, text, etc.)
shape Optional[Tuple[int, int]] None (rows, columns)
loaded bool False Whether data is loaded in memory
memory_usage_mb float 0.0 Memory usage in MB
null_count int 0 Total number of null values across all columns
row_count_estimate Optional[int] None Estimated row count from the database (TableSource only). Large tables (>10k rows) should use GROUP BY / aggregations instead of SELECT *.
table_size_warning str '' Size warning for the LLM when the table is large
is_active bool True Whether dataset is currently active
available bool True False when the source failed terminally; do not fetch
unavailable_reason Optional[str] None Why the dataset is unavailable
cache_ttl int 3600 Per-entry TTL in seconds for Redis cache
cache_key str '' Stable Redis cache key (from source.cache_key)
usage_do List[str] What this dataset should be used for (e.g. 'Revenue analysis by project')
usage_dont List[str] What this dataset should NOT be used for (e.g. 'Do not use for headcount')

Class DatasetManager

Dataset Catalog and toolkit for managing DataFrames and Queries.

As a Toolkit:

  • Exposes tools to the LLM: list_available(), get_metadata(), get_active(), etc.

As a Catalog:

  • Stores datasets (DataFrames or query slugs)
  • Manages active/inactive state (defaults to active)
  • Provides dataframes to PythonPandasTool on demand
  • Replaces MetadataTool with get_metadata() functionality

As a Metadata Engine:

  • Column type categorization (integer, float, datetime, categorical_text, text, etc.)
  • Per-column metrics guide generation
  • Comprehensive DataFrame info (shape, dtypes, memory, nulls, column types)
  • Data quality checks (NaN detection, completeness, duplicates)
Parameter Type Default Description
df_prefix str 'df'
generate_guide bool True
include_summary_stats bool False
auto_detect_types bool True
policy_guard Optional['DatasetPolicyGuard'] None
dataplane_guard Optional['DataPlanePolicyGuard'] None
usage_rules Optional[str] None
expose_admin_tools bool False
**kwargs {}

Attributes:

Attribute Type Description
tool_prefix str
DEFAULT_USAGE_RULES str
expose_admin_tools bool
df_guide str

Method DatasetManager.set_on_change

Register a callback invoked after dataset mutations (fetch, activate, deactivate).

set_on_change(callback: Callable[[], None]) -> None

Parameter Type Default Description
callback Callable[[], None]

Method DatasetManager.set_repl_locals_getter

Register an async callable that returns the REPL local variables.

Used by store_dataframe to look up a computed DataFrame by name from the python_repl_pandas execution environment. FEAT-380 (TASK-1944): async because the namespace lives in a worker process now — the getter awaits a PythonREPLTool.snapshot() round-trip.

set_repl_locals_getter(getter: Callable[[], Awaitable[Dict[str, Any]]]) -> None

Parameter Type Default Description
getter Callable[[], Awaitable[Dict[str, Any]]]

Method DatasetManager.drain_artifacts

Return accumulated artifacts and clear the internal list.

Called by the owning agent after a completion round to transfer artifacts (e.g. executed SQL queries) onto the AIMessage.

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

Returns: List[Dict[str, Any]]

Method DatasetManager.setup

Async init placeholder — can be extended for deferred prefetch.

setup() -> None

Method DatasetManager.categorize_columns

Categorize DataFrame columns into semantic data types.

Uses heuristics to distinguish between:

  • integer, float (numeric)
  • datetime
  • categorical, boolean
  • categorical_text (low-cardinality text)
  • text (high-cardinality text)

categorize_columns(df: pd.DataFrame) -> Dict[str, str]

Parameter Type Default Description
df pd.DataFrame DataFrame to categorize

Returns: Dict[str, str] — Dictionary mapping column names to type categories

Method DatasetManager.get_dataframe_info

Get comprehensive information about a DataFrame.

get_dataframe_info(df: pd.DataFrame) -> Dict[str, Any]

Parameter Type Default Description
df pd.DataFrame DataFrame to inspect

Returns: Dict[str, Any] — Dictionary with shape, columns, dtypes, memory usage, null counts, row/column counts, and optional column types.

Method DatasetManager.generate_metrics_guide

Generate per-column information guide with type, range, unique values, and nulls.

generate_metrics_guide(df: pd.DataFrame, columns: Optional[List[str]] = None) -> str

Parameter Type Default Description
df pd.DataFrame DataFrame to generate metrics for
columns Optional[List[str]] None Specific columns to include (defaults to all)

Returns: str — Formatted string with per-column metrics

Method DatasetManager.check_dataframes_for_nans

Check DataFrames for NaN/Null values.

check_dataframes_for_nans(names: Optional[List[str]] = None) -> List[str]

Parameter Type Default Description
names Optional[List[str]] None Specific dataset names to check (defaults to all active)

Returns: List[str] — List of warning messages describing where NaNs were found.

Method DatasetManager.add_dataset

Fetch data from any source and register the result as an in-memory DataFrame.

Unlike the lazy add_query / add_table_source methods, this executes the source immediately and stores the resulting DataFrame so the LLM can work with it via python_repl_pandas without extra fetch steps.

Exactly one of query_slug, query, table, or dataframe must be provided.

add_dataset(name: str, *, description: Optional[str] = None, query_slug: Optional[str] = None, query: Optional[str] = None, table: Optional[str] = None, dataframe: Optional[pd.DataFrame] = None, driver: Optional[str] = None, dsn: Optional[str] = None, credentials: Optional[Dict[str, Any]] = None, conditions: Optional[Dict[str, Any]] = None, sql: Optional[str] = None, filter: Optional[Dict[str, Any]] = None, metadata: Optional[Dict[str, Any]] = None, is_active: bool = True, permanent_filter: Optional[Dict[str, Any]] = None, computed_columns: Optional[List[Any]] = None, usage_guidance: Optional[Dict[str, List[str]]] = None) -> str

Parameter Type Default Description
name str Dataset name/identifier.
description Optional[str] None
query_slug Optional[str] None QuerySource slug — fetched via QS.
query Optional[str] None Raw SQL template (may contain {param} placeholders). Requires driver.
table Optional[str] None Fully-qualified table name (e.g. "schema.table"). Requires driver. Pass sql for a targeted SELECT or omit it to fetch all rows (SELECT * FROM table).
dataframe Optional[pd.DataFrame] None An already-loaded pandas DataFrame.
driver Optional[str] None AsyncDB driver ("pg", "bigquery", …). Required when using query or table.
dsn Optional[str] None Optional DSN override for the database connection.
credentials Optional[Dict[str, Any]] None Optional credentials dict for the database connection.
conditions Optional[Dict[str, Any]] None Parameter values for SQL-template placeholders (query mode) or QS conditions (query_slug mode).
sql Optional[str] None SQL statement for table mode. When omitted a SELECT * FROM <table> is executed.
filter Optional[Dict[str, Any]] None Optional dictionary-based filter applied to the fetched DataFrame before registration. Each key is a column name; scalar values use equality matching, list/tuple/set values use isin matching. All conditions are ANDed.
metadata Optional[Dict[str, Any]] None Optional metadata dict (description, etc.).
is_active bool True Whether the dataset is active (default True).
permanent_filter Optional[Dict[str, Any]] None Optional dict of equality conditions that are always applied when fetching data. For query_slug mode, merged into QS conditions. For table mode, injected as a WHERE clause. Ignored for dataframe and query modes.
computed_columns Optional[List[Any]] None
usage_guidance Optional[Dict[str, List[str]]] None

Returns: str — Confirmation message with shape.

Raises:

  • ValueError — If the source arguments are ambiguous or incomplete, or if a filter column is not found in the DataFrame.

Method DatasetManager.add_dataframe

Add a DataFrame to the catalog.

Datasets are ACTIVE by default when added, meaning they are immediately available for analysis.

add_dataframe(name: str, df: pd.DataFrame, description: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None, is_active: bool = True, computed_columns: Optional[List[Any]] = None, usage_guidance: Optional[Dict[str, List[str]]] = None) -> str

Parameter Type Default Description
name str Name/identifier for the dataset
df pd.DataFrame pandas DataFrame to add
description Optional[str] None Optional human-readable description of the dataset.
metadata Optional[Dict[str, Any]] None Optional metadata dictionary with description, column info
is_active bool True Whether dataset is active (default True)
computed_columns Optional[List[Any]] None Optional list of ComputedColumnDef objects applied post-materialization. Applied immediately when df is provided directly.
usage_guidance Optional[Dict[str, List[str]]] None Optional dict with do and dont lists that tell the LLM what this dataset should (and should not) be used for. Example:: {"do": ["Revenue analysis by project"], "dont": ["Do not use for headcount queries"]}

Returns: str — Confirmation message

Method DatasetManager.add_dataframe_from_file

Create and add a DataFrame from a CSV or Excel file.

File type detection is based on extension. For Excel files, a default engine is selected unless explicitly provided via kwargs.

add_dataframe_from_file(name: str, path: Union[str, PathLike[str]], metadata: Optional[Dict[str, Any]] = None, is_active: bool = True, **kwargs: Any) -> str

Parameter Type Default Description
name str Name/identifier for the dataset
path Union[str, PathLike[str]] Path to the CSV/Excel file
metadata Optional[Dict[str, Any]] None Optional metadata dictionary with description, column info
is_active bool True Whether dataset is active (default True)
**kwargs Any {} Passed directly to pandas read_csv/read_excel

Returns: str — Confirmation message from add_dataframe

Method DatasetManager.load_file

Load a CSV or Excel file for LLM context.

Unlike add_dataframe_from_file() which converts to DataFrame, this method preserves the file's structural layout and produces clean markdown that can be passed directly to the LLM.

load_file(name: str, path: Union[str, Path], metadata: Optional[Dict[str, Any]] = None, max_rows_per_table: int = 200, output_format: str = 'markdown') -> str

Parameter Type Default Description
name str Identifier for the file in the catalog.
path Union[str, Path] Path to CSV or Excel file.
metadata Optional[Dict[str, Any]] None Optional metadata.
max_rows_per_table int 200 Max rows per extracted table (token budget).
output_format str 'markdown' 'markdown', 'csv', or 'json'.

Returns: str — Structural summary string.

Method DatasetManager.get_file_context

Get the full markdown context for a loaded file.

get_file_context(name: str) -> str

Parameter Type Default Description
name str File identifier used in load_file().

Returns: str — All table markdown concatenated with headers.

Method DatasetManager.get_file_table

Get markdown for a specific table from a loaded file.

get_file_table(name: str, table_id: str) -> str

Parameter Type Default Description
name str File identifier used in load_file().
table_id str Table ID (e.g. 'T1', 'table').

Returns: str — Markdown string for the requested table.

Method DatasetManager.add_source

Register a pre-built DataSource instance with optional CapabilityRegistry hook.

Provides a generic entry point for registering any DataSource subclass directly, with automatic capability indexing when a registry is supplied. The source is wrapped in a DatasetEntry and stored under the source's name attribute (or cache_key as fallback).

add_source(source, capability_registry=None) -> str

Parameter Type Default Description
source A DataSource subclass instance to register. Should have a name attribute; cache_key is used as the fallback key.
capability_registry None Optional CapabilityRegistry. When provided, calls registry.register_from_datasource(source) so the source is discoverable by the intent router.

Returns: str — Confirmation message string.

Raises:

  • ValueError — If source does not have a cache_key property.

Method DatasetManager.add_semantic

Register a dataset backed by a governed Semantic Layer model (FEAT-880).

Exactly one of toolkit or (models_dir and dialect) is required. When the toolkit is built here and toolkit_kwargs carries no dataplane_guard, the manager's own guard is passed to it.

add_semantic(name: str, *, model: str, toolkit: Optional[Any] = None, models_dir: Optional[Union[str, Path]] = None, dialect: Optional[str] = None, default_query: Optional[Dict[str, Any]] = None, description: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None, is_active: bool = True, usage_guidance: Optional[Dict[str, List[str]]] = None, **toolkit_kwargs: Any) -> str

Parameter Type Default Description
name str Name/identifier for the dataset.
model str Semantic model the dataset is bound to.
toolkit Optional[Any] None An existing SemanticLayerToolkit to bind.
models_dir Optional[Union[str, Path]] None Directory of semantic model definitions (builds a toolkit).
dialect Optional[str] None SQL dialect of the toolkit built from models_dir.
default_query Optional[Dict[str, Any]] None Query used when fetch_dataset gets no conditions.
description Optional[str] None Optional description (defaults to the source's own text).
metadata Optional[Dict[str, Any]] None Optional metadata dictionary.
is_active bool True Whether dataset is active (default True).
usage_guidance Optional[Dict[str, List[str]]] None Optional do/dont lists for the LLM.
**toolkit_kwargs Any {} Extra keyword arguments for the built toolkit.

Returns: str — Confirmation message.

Raises:

  • ImportError — when ai-parrot-semantic is not installed.
  • ValueError — when both or neither source of the toolkit is given.

Method DatasetManager.add_query

Register a query slug for lazy loading.

add_query(name: str, query_slug: str, description: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None, is_active: bool = True, permanent_filter: Optional[Dict[str, Any]] = None, query_filter: Optional[Dict[str, Any]] = None, computed_columns: Optional[List[Any]] = None, usage_guidance: Optional[Dict[str, List[str]]] = None) -> str

Parameter Type Default Description
name str Name/identifier for the dataset.
query_slug str QuerySource slug to load data from.
description Optional[str] None Optional human-readable description of the dataset.
metadata Optional[Dict[str, Any]] None Optional metadata dictionary.
is_active bool True Whether dataset is active (default True).
permanent_filter Optional[Dict[str, Any]] None Optional dict of equality conditions that are always merged into every fetch() call. Permanent filter keys take precedence over runtime params.
query_filter Optional[Dict[str, Any]] None Alias for permanent_filter. When both are provided, permanent_filter takes precedence.
computed_columns Optional[List[Any]] None Optional list of ComputedColumnDef objects applied post-materialization.
usage_guidance Optional[Dict[str, List[str]]] None Optional dict with do and dont lists that tell the LLM what this dataset should (and should not) be used for.

Returns: str — Confirmation message.

Method DatasetManager.add_table_source

Register a database table with schema prefetch.

Runs INFORMATION_SCHEMA query on registration to discover column names and types. The LLM receives schema information without fetching any rows.

add_table_source(name: str, table: str, driver: str, *, description: Optional[str] = None, dsn: Optional[str] = None, credentials: Optional[Dict[str, Any]] = None, metadata: Optional[Dict[str, Any]] = None, cache_ttl: int = 3600, strict_schema: bool = True, permanent_filter: Optional[Dict[str, Any]] = None, query_filter: Optional[Dict[str, Any]] = None, allowed_columns: Optional[List[str]] = None, no_cache: bool = False, computed_columns: Optional[List[Any]] = None, usage_guidance: Optional[Dict[str, List[str]]] = None) -> str

Parameter Type Default Description
name str Name/identifier for the dataset.
table str Fully-qualified table name, e.g. "public.orders".
driver str AsyncDB driver name, e.g. "pg", "bigquery", "mysql".
description Optional[str] None
dsn Optional[str] None Optional DSN string.
credentials Optional[Dict[str, Any]] None Optional credentials dict.
metadata Optional[Dict[str, Any]] None Optional metadata dict with description, etc.
cache_ttl int 3600 Redis cache TTL in seconds (default 3600).
strict_schema bool True If True (default), raise on prefetch failure.
permanent_filter Optional[Dict[str, Any]] None Optional dict of equality conditions that are always injected as a WHERE clause into every fetch() SQL. Scalar values produce col = 'val'; list/tuple values produce col IN ('a', 'b').
query_filter Optional[Dict[str, Any]] None Alias for permanent_filter. When both are provided, permanent_filter takes precedence.
allowed_columns Optional[List[str]] None Optional list of column names to restrict access. When set, only these columns appear in the schema, guide, and metadata. SQL queries referencing other columns are rejected.
no_cache bool False If True, skip the Redis cache layer entirely for this table source. Every fetch_dataset call executes the SQL directly against the database. Useful for small/parameter tables where fresh data is always needed.
computed_columns Optional[List[Any]] None
usage_guidance Optional[Dict[str, List[str]]] None

Returns: str — Confirmation message with column count, driver, and restriction info.

Method DatasetManager.add_sql_source

Register a parameterized SQL source. Sync — no prefetch needed.

The SQL may use {param} placeholders injected at fetch time.

add_sql_source(name: str, sql: str, driver: str, *, description: Optional[str] = None, dsn: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None, cache_ttl: int = 3600, computed_columns: Optional[List[Any]] = None, usage_guidance: Optional[Dict[str, List[str]]] = None) -> str

Parameter Type Default Description
name str Name/identifier for the dataset.
sql str SQL template with optional {param} placeholders.
driver str AsyncDB driver name, e.g. "pg", "bigquery", "mysql".
description Optional[str] None Optional human-readable description of the dataset.
dsn Optional[str] None Optional DSN string.
metadata Optional[Dict[str, Any]] None Optional metadata dict.
cache_ttl int 3600 Redis cache TTL in seconds (default 3600).
computed_columns Optional[List[Any]] None Optional list of ComputedColumnDef objects applied post-materialization.
usage_guidance Optional[Dict[str, List[str]]] None

Returns: str — Confirmation message.

Method DatasetManager.add_airtable_source

Register an Airtable table source and optionally fetch immediately.

add_airtable_source(name: str, base_id: str, table: str, api_key: Optional[str] = None, view: Optional[str] = None, description: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None, cache_ttl: int = 3600, fetch_on_create: bool = True, computed_columns: Optional[List[Any]] = None) -> str

Parameter Type Default Description
name str
base_id str
table str
api_key Optional[str] None
view Optional[str] None
description Optional[str] None
metadata Optional[Dict[str, Any]] None
cache_ttl int 3600
fetch_on_create bool True
computed_columns Optional[List[Any]] None

Returns: str

Method DatasetManager.add_smartsheet_source

Register a Smartsheet source and optionally fetch immediately.

add_smartsheet_source(name: str, sheet_id: str, access_token: Optional[str] = None, description: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None, cache_ttl: int = 3600, fetch_on_create: bool = True, computed_columns: Optional[List[Any]] = None) -> str

Parameter Type Default Description
name str
sheet_id str
access_token Optional[str] None
description Optional[str] None
metadata Optional[Dict[str, Any]] None
cache_ttl int 3600
fetch_on_create bool True
computed_columns Optional[List[Any]] None

Returns: str

Method DatasetManager.add_iceberg_source

Register an Apache Iceberg table with schema and row-count prefetch.

Calls source.prefetch_schema() (loads table metadata) and source.prefetch_row_count() (COUNT(*) estimate) on registration. The LLM receives column names, types, and size info without fetching any rows.

add_iceberg_source(name: str, table_id: str, catalog_params: Dict[str, Any], *, description: Optional[str] = None, factory: str = 'pandas', credentials: Optional[Dict[str, Any]] = None, dsn: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None, cache_ttl: int = 3600, no_cache: bool = False, is_active: bool = True, computed_columns: Optional[List[Any]] = None) -> str

Parameter Type Default Description
name str Dataset name/identifier.
table_id str Fully-qualified Iceberg table identifier, e.g. "demo.cities".
catalog_params Dict[str, Any] asyncdb iceberg driver connection params (uri, warehouse, catalog type, etc.).
description Optional[str] None Optional human-readable description.
factory str 'pandas' asyncdb output factory (default "pandas").
credentials Optional[Dict[str, Any]] None Optional credentials dict for the catalog.
dsn Optional[str] None Optional DSN string (rarely used for Iceberg).
metadata Optional[Dict[str, Any]] None Optional metadata dict.
cache_ttl int 3600 Redis cache TTL in seconds (default 3600).
no_cache bool False If True, skip the Redis cache layer for this source.
is_active bool True Whether the dataset is active (default True).
computed_columns Optional[List[Any]] None

Returns: str — Confirmation message with column count and catalog type.

Method DatasetManager.add_mongo_source

Register a MongoDB/DocumentDB collection with schema prefetch.

Calls source.prefetch_schema() via find_one() to infer field names and Python types from a single document. Read-only — every fetch_dataset() call requires a filter dict and a projection dict.

add_mongo_source(name: str, collection: str, database: str, *, description: Optional[str] = None, credentials: Optional[Dict[str, Any]] = None, dsn: Optional[str] = None, required_filter: bool = True, metadata: Optional[Dict[str, Any]] = None, cache_ttl: int = 3600, no_cache: bool = False, is_active: bool = True, computed_columns: Optional[List[Any]] = None) -> str

Parameter Type Default Description
name str Dataset name/identifier.
collection str MongoDB collection name, e.g. "orders".
database str MongoDB database name, e.g. "mydb".
description Optional[str] None Optional human-readable description.
credentials Optional[Dict[str, Any]] None Optional credentials dict with host/port/user/password. Used when dsn is None.
dsn Optional[str] None Optional MongoDB connection string (DSN).
required_filter bool True If True (default), fetch_dataset() raises ValueError when no filter is provided.
metadata Optional[Dict[str, Any]] None Optional metadata dict.
cache_ttl int 3600 Redis cache TTL in seconds (default 3600).
no_cache bool False If True, skip the Redis cache layer for this source.
is_active bool True Whether the dataset is active (default True).
computed_columns Optional[List[Any]] None

Returns: str — Confirmation message with field count.

Method DatasetManager.add_deltatable_source

Register a Delta Lake table with schema and row-count prefetch.

Calls source.prefetch_schema() (reads Delta metadata) and source.prefetch_row_count() (COUNT(*) estimate) on registration. The LLM receives column names, types, and size info without fetching any rows.

For S3 paths (s3://...), credentials are resolved automatically via AWSInterface unless explicit credentials are provided.

add_deltatable_source(name: str, path: str, *, description: Optional[str] = None, table_name: Optional[str] = None, mode: str = 'error', credentials: Optional[Dict[str, Any]] = None, metadata: Optional[Dict[str, Any]] = None, cache_ttl: int = 3600, no_cache: bool = False, is_active: bool = True, computed_columns: Optional[List[Any]] = None) -> str

Parameter Type Default Description
name str Dataset name/identifier.
path str Path to the Delta table — local, s3://, or gs://.
description Optional[str] None Optional human-readable description.
table_name Optional[str] None DuckDB alias used in SQL queries. Defaults to the uppercased name.
mode str 'error' Write mode for creation helpers: overwrite, append, error, ignore. Defaults to "error".
credentials Optional[Dict[str, Any]] None Optional credentials/storage-options dict. For S3, AWSInterface is used automatically when None.
metadata Optional[Dict[str, Any]] None Optional metadata dict.
cache_ttl int 3600 Redis cache TTL in seconds (default 3600).
no_cache bool False If True, skip the Redis cache layer for this source.
is_active bool True Whether the dataset is active (default True).
computed_columns Optional[List[Any]] None

Returns: str — Confirmation message with column count and path.

Method DatasetManager.add_composite_dataset

Register a virtual composite dataset that JOINs existing datasets.

Parses joins dicts into JoinSpec models, validates that all referenced component datasets are already registered, creates a CompositeDataSource, wraps it in a DatasetEntry, and registers the composite in _datasets.

add_composite_dataset(name: str, joins: List[Dict[str, Any]], *, description: str = '', computed_columns: Optional[List[Any]] = None, is_active: bool = True, metadata: Optional[Dict[str, Any]] = None) -> str

Parameter Type Default Description
name str Dataset name/identifier for the composite.
joins List[Dict[str, Any]] List of dicts, each with keys left, right, on and optionally how (default "inner") and suffixes. Every referenced dataset must already be registered.
description str '' Optional human-readable description forwarded to the composite source and entry.
computed_columns Optional[List[Any]] None Optional list of ComputedColumnDef objects applied post-materialization on the JOIN result.
is_active bool True Whether the dataset is active (default True).
metadata Optional[Dict[str, Any]] None Optional metadata dictionary.

Returns: str — Confirmation message including the join topology.

Raises:

  • ValueError — If any referenced component dataset is not registered.

Method DatasetManager.create_iceberg_from_dataframe

Write a DataFrame to a new Iceberg table and register it as a dataset.

Creates the Iceberg namespace (if needed), infers a PyArrow schema from the DataFrame, writes the data, then registers the table with add_iceberg_source().

create_iceberg_from_dataframe(name: str, df: 'pd.DataFrame', table_id: str, *, namespace: str = 'default', catalog_params: Optional[Dict[str, Any]] = None, description: Optional[str] = None, mode: str = 'overwrite') -> str

Parameter Type Default Description
name str Dataset name/identifier for the new source.
df 'pd.DataFrame' DataFrame whose data is written to the Iceberg table.
table_id str Fully-qualified target table identifier, e.g. "demo.cities".
namespace str 'default' Iceberg namespace (catalog namespace) to create the table in. Defaults to "default".
catalog_params Optional[Dict[str, Any]] None asyncdb iceberg driver connection params. Required — raises ValueError if None.
description Optional[str] None Optional human-readable description.
mode str 'overwrite' Write mode for the data write step: "overwrite" or "append". Defaults to "overwrite".

Returns: str — Confirmation message from add_iceberg_source().

Raises:

  • ValueError — If catalog_params is not provided.
  • RuntimeError — If table creation or write fails.

Method DatasetManager.replay_datasources

Register agent-level datasource descriptors (FEAT-593). Returns registered names.

Each item is a DatasourceSpec model or dict. A failing entry is logged at WARNING (never with secret values) and skipped.

replay_datasources(datasources: Sequence[Any]) -> list[str]

Parameter Type Default Description
datasources Sequence[Any] Validated datasource models or their dictionary representations.

Returns: list[str] — Names of datasource descriptors registered successfully.

Method DatasetManager.create_deltatable_from_parquet

Create a Delta table from a Parquet file and register it as a dataset.

Calls DeltaTableSource.create_from_parquet() to write the Delta table, then registers the result with add_deltatable_source().

create_deltatable_from_parquet(name: str, parquet_path: str, delta_path: str, *, table_name: Optional[str] = None, mode: str = 'overwrite', description: Optional[str] = None) -> str

Parameter Type Default Description
name str Dataset name/identifier for the new source.
parquet_path str Path to the source Parquet file (local or cloud).
delta_path str Target path for the new Delta table — local, s3://, or gs://.
table_name Optional[str] None DuckDB alias for SQL queries against this table. Defaults to the uppercased name.
mode str 'overwrite' Write mode: "overwrite", "append", "error", "ignore". Defaults to "overwrite".
description Optional[str] None Optional human-readable description.

Returns: str — Confirmation message from add_deltatable_source().

Raises:

  • RuntimeError — If Delta table creation fails.

Method DatasetManager.remove

Remove a dataset from the catalog.

remove(name: str) -> str

Parameter Type Default Description
name str

Returns: str

Method DatasetManager.set_query_loader

Set the query loader callable (from PandasAgent).

set_query_loader(loader: Any) -> None

Parameter Type Default Description
loader Any

Method DatasetManager.activate

Mark datasets as active for use in the session.

activate(names: Union[str, List[str]]) -> List[str]

Parameter Type Default Description
names Union[str, List[str]]

Returns: List[str]

Method DatasetManager.deactivate

Mark datasets as inactive (exclude from session).

deactivate(names: Union[str, List[str]]) -> List[str]

Parameter Type Default Description
names Union[str, List[str]]

Returns: List[str]

Method DatasetManager.get_active_dataframes

Get loaded active frames safe to bind into a shared execution namespace.

Self-governed frames stay in their subject's entry slot and are only returned through subject-scoped fetches, never bulk REPL synchronization.

get_active_dataframes() -> Dict[str, pd.DataFrame]

Returns: Dict[str, pd.DataFrame]

Method DatasetManager.get_active_dataframes_lazy

Get non-governed active frames, loading from queries if needed.

get_active_dataframes_lazy() -> Dict[str, pd.DataFrame]

Returns: Dict[str, pd.DataFrame]

Method DatasetManager.get_dataset_entry

Get a dataset entry by name or alias.

get_dataset_entry(name: str) -> Optional[DatasetEntry]

Parameter Type Default Description
name str

Returns: Optional[DatasetEntry]

Method DatasetManager.list_dataframes

List all loaded DataFrames with detailed info.

Returns original names as keys with alias, shape, columns, memory usage, null count, and column types.

list_dataframes() -> Dict[str, Dict[str, Any]]

Returns: Dict[str, Dict[str, Any]]

Method DatasetManager.get_dataframe_summary

Get detailed summary for a specific DataFrame.

Accepts both original name and alias.

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

Parameter Type Default Description
name str Dataset name or alias

Returns: Dict[str, Any] — Comprehensive DataFrame info dictionary

Raises:

  • ValueError — If dataset not found

Method DatasetManager.add_computed_column

Add a computed column to an existing dataset at runtime.

The function must be registered in the computed-function registry. If the dataset is already loaded, the column is applied immediately and the guide is regenerated.

add_computed_column(dataset_name: str, column_name: str, func: str, columns: List[str], description: str = '', **kwargs: Any) -> str

Parameter Type Default Description
dataset_name str Name or alias of the target dataset.
column_name str Name of the new column to create.
func str Function name from the computed-function registry. Call list_available_functions() to see available functions.
columns List[str] Source column names the function operates on (in order).
description str '' Optional human-readable description of the new column.
**kwargs Any {} Extra keyword arguments forwarded to the function (e.g. operation="subtract" for math_operation).

Returns: str — Confirmation message if successful, or an error message if the function/dataset/columns could not be resolved.

Method DatasetManager.list_available_functions

List all available computed-column functions.

Returns the sorted list of function names that can be used with add_computed_column() or in ComputedColumnDef.func.

list_available_functions() -> List[str]

Returns: List[str] — Sorted list of registered function name strings.

Method DatasetManager.get_tools_filtered

Filter toolkit tools by resolver and then by dataset policy.

Delegates to super().get_tools_filtered() for the standard tool-level PBAC pass, then consults DatasetPolicyGuard.filter_datasets to compute the set of accessible datasets. Tools whose associated dataset name is denied are excluded; generic tools (no specific dataset association) are always kept.

When self._policy_guard is None, returns the base resolver result unchanged (opt-in backwards compat).

get_tools_filtered(permission_context: 'PermissionContext', resolver: 'AbstractPermissionResolver') -> List

Parameter Type Default Description
permission_context 'PermissionContext' User context for permission filtering.
resolver 'AbstractPermissionResolver' Permission resolver for the standard tool-level pass.

Returns: List — Filtered list of AbstractTool instances.

Method DatasetManager.list_datasets

List all datasets in the catalog with their status.

CALL THIS FIRST before any analysis. Shows which datasets are already loaded (ready for python_repl_pandas) and which need fetch_dataset.

Each entry includes: name, python_variable, python_alias, loaded status, shape, columns, and source type.

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

Returns: List[Dict[str, Any]] — List of dataset info dicts. Check 'loaded' field to know if data is already available in python_repl_pandas.

Method DatasetManager.list_available

Alias for list_datasets (backward compatibility).

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

Returns: List[Dict[str, Any]]

Method DatasetManager.get_active

Get the names of all currently active datasets.

Active datasets are available for analysis in python_repl_pandas.

get_active() -> List[str]

Returns: List[str]

Method DatasetManager.get_datasets_summary

Generate a bullet-list summary of all active datasets with descriptions.

Each entry shows the dataset name and its description. Datasets without a description show (no description). Inactive datasets are excluded.

Used both as an LLM-callable tool and internally for system prompt injection via _generate_dataframe_guide().

get_datasets_summary() -> str

Returns: str — Markdown-formatted bullet list of active datasets, or empty string when no active datasets are registered.

Method DatasetManager.get_metadata

Get comprehensive metadata about a dataset.

get_metadata(name: str, include_eda: bool = False, include_samples: bool = True, include_column_stats: bool = False, include_metrics_guide: bool = False, column: Optional[str] = None) -> Dict[str, Any]

Parameter Type Default Description
name str Dataset name or alias (e.g., 'sales_data' or 'df1')
include_eda bool False Include EDA summary (row counts, missing values, memory)
include_samples bool True Include sample rows from the DataFrame
include_column_stats bool False Include detailed statistics for columns
include_metrics_guide bool False Include formatted per-column metrics guide
column Optional[str] None Get metadata for a specific column only

Returns: Dict[str, Any] — Comprehensive dataset metadata including schema, EDA, and samples

Method DatasetManager.activate_datasets

Activate datasets for use in analysis.

Use this when you want to include specific datasets in the current session. By default, all datasets are active when added.

activate_datasets(names: List[str]) -> str

Parameter Type Default Description
names List[str] List of dataset names or aliases to activate

Returns: str — Confirmation message

Method DatasetManager.deactivate_datasets

Deactivate datasets to exclude them from the current session.

Deactivated datasets will not be available in python_repl_pandas until they are activated again.

deactivate_datasets(names: List[str]) -> str

Parameter Type Default Description
names List[str] List of dataset names or aliases to deactivate

Returns: str — Confirmation message

Method DatasetManager.remove_dataset

Remove a dataset from the catalog entirely.

This permanently removes the dataset. Use deactivate_datasets if you only want to temporarily exclude it. Protected (core) datasets cannot be removed.

remove_dataset(name: str) -> str

Parameter Type Default Description
name str Dataset name or alias to remove

Returns: str — Confirmation message

Method DatasetManager.get_dataframe

Get a DataFrame by name or alias.

Returns the DataFrame info and sample data. Use this to retrieve a specific dataset for inspection or further operations.

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

Parameter Type Default Description
name str Dataset name or alias (e.g., 'sales_data' or 'df1')

Returns: Dict[str, Any] — DataFrame information including shape, columns, and sample rows

Method DatasetManager.store_dataframe

Store a computed DataFrame from python_repl_pandas into the catalog.

Use this ONLY when the user explicitly asks to save/persist a result for reuse in future questions. Storing is NEVER required to answer the current question — to return a result, assign it to a variable and declare it in data_variable instead.

Do NOT call this for intermediate variables, for one-off answers, or for datasets that already exist in the catalog.

store_dataframe(name: str, description: str = '') -> str

Parameter Type Default Description
name str Variable name as it exists in python_repl_pandas.
description str '' Short description of what this dataset contains.

Returns: str — Confirmation message or error.

Method DatasetManager.fetch_dataset

Materialize a dataset by fetching data from its source.

Use this to load data into memory before analysing it.

  • For TableSource: 'sql' is required — provide a SELECT using the schema columns.
  • For SQLQuerySource: 'conditions' injects {param} values into the SQL template.
  • For QuerySlugSource / InMemorySource: no extra params needed.

After successful materialization the response includes the data (for small result sets) or sample rows (for large ones), plus schema and shape.

SQL QUERY STRATEGY for TableSource (CRITICAL — READ CAREFULLY):

NEVER fetch raw rows to aggregate in Python. ALWAYS push aggregation to the database using GROUP BY / COUNT / SUM / AVG / MIN / MAX in SQL.

DECISION TREE — follow this BEFORE writing your SQL:

  1. Does the question involve averages, totals, counts, or rankings? → Write a GROUP BY query. The database handles millions of rows efficiently; pandas on the same data wastes memory and time.
  2. Does the question ask for "monthly", "weekly", "daily" summaries? → Use DATE_TRUNC + GROUP BY, NOT fetch-all-then-resample.
  3. Do you need a filtered subset? → Use WHERE + LIMIT.
  4. Only fetch individual rows when the question truly requires row-level detail (e.g., "show me the raw records for kiosk X").

EXAMPLES — follow these patterns: ✅ CORRECT (monthly averages): "SELECT kiosk_id, DATE_TRUNC('month', history_date) AS month, AVG(depletion_rate) AS avg_depletion, AVG(fill_rate) AS avg_fill FROM schema.daily_summary WHERE history_date BETWEEN '2025-01-01' AND '2025-12-31' GROUP BY kiosk_id, month ORDER BY month" ✅ CORRECT (top N by metric): "SELECT kiosk_id, SUM(units) AS total_units FROM schema.daily_summary GROUP BY kiosk_id ORDER BY total_units DESC LIMIT 20" ❌ WRONG (fetches millions of rows then aggregates in pandas): "SELECT kiosk_id, history_date, depletion_rate, fill_rate FROM schema.daily_summary WHERE history_date >= '2025-01-01' AND history_date <= '2025-12-31'"

The database is orders of magnitude faster at aggregation than pandas. A query returning 2000 kiosks × 365 days = 730K rows is ALWAYS wrong when the user asked for monthly averages — push that to SQL.

IMPORTANT: The response includes 'python_variable' and 'python_alias' fields. These are the ONLY valid variable names in python_repl_pandas. Always use one of these exact names — never modify or invent new names.

fetch_dataset(name: str, sql: Optional[str] = None, conditions: Optional[Dict[str, Any]] = None, force_refresh: bool = False) -> Dict[str, Any]

Parameter Type Default Description
name str Dataset name or alias.
sql Optional[str] None SQL query string (required for TableSource). MUST include GROUP BY with aggregate functions (AVG, SUM, COUNT, etc.) when the question involves summaries, averages, or rankings. NEVER fetch all rows to aggregate in pandas.
conditions Optional[Dict[str, Any]] None Dict of {param: value} pairs for SQLQuerySource templates. For a semantic dataset, conditions IS the semantic query: metrics, dimensions, time_dimensions, filters, order_by, limit, offset and saved_query (sql is ignored). A semantic dataset holds the result of ONE query — call fetch_dataset again with new conditions whenever any of those fields change, instead of re-aggregating the previous result in pandas. When the response has semantic.truncated set, the policy row limit was reached: aggregate further in the semantic query.
force_refresh bool False If True, bypass caches and re-fetch from source.

Returns: Dict[str, Any] — Dict with status, shape, column schema, data or sample rows, and python_variable/python_alias for use in python_repl_pandas.

Method DatasetManager.evict_dataset

Release a materialized dataset from memory.

Source reference and schema are retained. The dataset can be re-fetched with fetch_dataset later.

evict_dataset(name: str) -> str

Parameter Type Default Description
name str Dataset name or alias.

Returns: str — Confirmation message.

Method DatasetManager.get_source_schema

Return the schema (column → type) for a registered source.

For TableSource: schema is available before materialization (prefetched on registration). For other source types: requires a prior fetch_dataset call.

get_source_schema(name: str) -> str

Parameter Type Default Description
name str Dataset name or alias.

Returns: str — Formatted schema string or error message.

Method DatasetManager.check_data_quality

Run data quality checks on datasets.

Checks for NaN/null values, duplicates, and completeness across specified datasets or all active datasets.

check_data_quality(names: Optional[List[str]] = None) -> Dict[str, Any]

Parameter Type Default Description
names Optional[List[str]] None Specific dataset names to check (defaults to all active)

Returns: Dict[str, Any] — Data quality report with NaN warnings and completeness metrics

Method DatasetManager.get_guide

Return the current DataFrame guide.

get_guide() -> str

Returns: str

Method DatasetManager.get_usage_rules

Return the decision rules an agent should inject into its system prompt.

These are tool-level (not agent-specific): any agent driving a DatasetManager benefits from the same guidance on when to use loaded DataFrames vs fetch_dataset vs get_metadata. Returns the per-instance override when one was passed to the constructor, otherwise :attr:DEFAULT_USAGE_RULES. An explicit empty string disables the block.

get_usage_rules() -> str

Returns: str — The usage-rules markdown block, or "" when disabled.

Method DatasetManager.materialize

On-demand materialization with Redis Parquet caching.

Flow for sources WITHOUT built-in caching (SQL, Table, InMemory):

  1. If already loaded and not force_refresh → return in-memory _df.
  2. Check Redis: hit → deserialize Parquet → set entry._df → return.
  3. Miss → entry.materialize(**params) → _cache_df → return.

Flow for sources WITH built-in caching (QuerySlugSource, MultiQuerySlugSource):

  1. If already loaded and not force_refresh → return in-memory _df.
  2. Delegate entirely to source.fetch(force_refresh=force_refresh, **params). The source bubbles force_refresh → QS refresh condition so QS handles its own cache invalidation. DatasetManager does NOT wrap these sources in a redundant Redis layer.

materialize(name: str, force_refresh: bool = False, **params) -> pd.DataFrame

Parameter Type Default Description
name str Dataset name or alias.
force_refresh bool False If True, bypass in-memory and any cache; re-fetch from source.
**params {} Passed to source.fetch() (e.g. sql= for TableSource).

Returns: pd.DataFrame — The materialized DataFrame.

Raises:

  • ValueError — If dataset not found.

Method DatasetManager.evict

Release a materialized DataFrame from memory.

Source reference and schema are retained; dataset can be re-materialized.

evict(name: str) -> str

Parameter Type Default Description
name str Dataset name or alias.

Returns: str — Confirmation message.

Method DatasetManager.evict_all

Release all materialized DataFrames from memory.

evict_all() -> str

Returns: str — Confirmation message with count.

Method DatasetManager.evict_table_sources

Evict all loaded TableSource DataFrames from memory.

Table sources contain query-specific data (different columns/filters per SQL). Evicting them between conversation turns forces the LLM to call fetch_dataset again with a fresh SQL appropriate to the new question.

Eagerly-loaded DataFrames (InMemorySource) and QuerySlugSources are NOT evicted — they are complete datasets, not query fragments.

evict_table_sources() -> int

Returns: int — Number of datasets evicted.

Method DatasetManager.evict_unactive

Release inactive (is_active=False) materialized DataFrames from memory.

evict_unactive() -> str

Returns: str — Confirmation message with count.

Method DatasetManager.load_data

Deprecated: bulk query-loading helper kept for PandasAgent backward compat.

For new code use add_query() + materialize() instead.

load_data(query: Union[List[str], Dict, str], agent_name: str, refresh: bool = False, cache_expiration: int = 48, no_cache: bool = False, **kwargs) -> Dict[str, pd.DataFrame]

Parameter Type Default Description
query Union[List[str], Dict, str]
agent_name str
refresh bool False
cache_expiration int 48
no_cache bool False
**kwargs {}

Returns: Dict[str, pd.DataFrame]

Method DatasetManager.define_filters

Validate and store common-field filter definitions on this instance.

Each definition is validated against the datasets registered on this DatasetManager:

  • Column coverage — at least one registered dataset with a known schema should contain the target column(s). If no such dataset is found a warning is logged (non-fatal: datasets may not be materialized yet or may be added later).
  • Spatial kind — when kind="spatial" every registered dataset is checked against the spatial profile registry via get_spatial_profile. If no registered dataset has a spatial profile a ValueError is raised.
  • Duplicate names — replacing an existing definition is allowed and logged at DEBUG level.

The definitions are stored in self._filter_defs (instance-scoped, never global).

define_filters(definitions: List[FilterDefinition]) -> None

Parameter Type Default Description
definitions List[FilterDefinition] List of validated :class:FilterDefinition instances.

Raises:

  • ValueError — When kind="spatial" and no registered dataset has a registered spatial profile.

Method DatasetManager.get_filter_values

Return distinct values for a named filter.

Resolution order:

  1. Declared values_source (from the FilterDefinition):
    • query_slug → run the slug via the query loader and extract the column (values_source.column) from the result.
    • column only → infer from datasets; restrict to values_source.dataset if specified.
  2. Inference fallback — union of distinct values from every in-memory dataset that has the target column.

Results are de-duplicated, sorted, and capped at cardinality_cap (default 1000). A simple per-instance in-memory cache avoids redundant work within a session.

get_filter_values(name: str, *, cardinality_cap: int = 1000) -> List[Any]

Parameter Type Default Description
name str The filter definition name to look up.
cardinality_cap int 1000 Maximum number of distinct values to return. Values beyond the cap are truncated (a warning is logged).

Returns: List[Any] — Sorted, de-duplicated list of distinct values.

Raises:

  • KeyError — When no filter definition with name exists.

Method DatasetManager.clear_filter_values_cache

Invalidate the filter-values cache.

Called automatically by add_dataframe and related dataset-mutation methods to evict stale entries when datasets change. May also be called explicitly to force a full re-scan on the next get_filter_values call.

clear_filter_values_cache(name: Optional[str] = None) -> None

Parameter Type Default Description
name Optional[str] None Dataset name to invalidate. If None, clears the entire cache.

Method DatasetManager.get_filter_schema

Serialize the filter catalog for the frontend.

Returns one entry per stored FilterDefinition, including which registered datasets have the target column(s) (the "applicable" set).

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

Returns: List[Dict[str, Any]] — List of dicts, one per filter::

[ { "name": "region", "kind": "categorical", "ops": ["eq", "ne", "in"], "label": "Region", "required": False, "datasets": ["stores", "sites"], # datasets with the column }, ... ] Datasets whose schema has not been loaded yet (_column_types is empty and _df is None) are omitted from datasets — they are not excluded, just unknown.

Method DatasetManager.suggest_filters

Propose FilterDefinitions from column introspection (opt-in, no side effects).

Scans loaded datasets and proposes filter definitions for columns that are present in at least min_datasets datasets with a known schema.

Mapping from column kind to FilterDefinition:

  • categorical / categorical_text → kind="categorical", ops ["eq","ne","in","not_in"].
  • integer / float → kind="numeric", ops ["range","eq"].
  • datetime → kind="temporal", ops ["range"].
  • Columns in a registered spatial profile (lat/lng pairs or geom col) → kind="spatial", ops ["radius"].

suggest_filters(min_datasets: int = 1) -> List[FilterDefinition]

Parameter Type Default Description
min_datasets int 1 Minimum number of datasets that must have the column for a suggestion to be made (default 1).

Returns: List[FilterDefinition] — List of proposed :class:FilterDefinition instances. This method has no side effects — definitions are NOT stored.

Method DatasetManager.list_filters

List all defined common-field filters and their applicable datasets.

Returns the filter schema — one entry per stored filter definition with its name, kind, supported operators, applicable datasets, and metadata. Call this to discover what filters are available before applying them.

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

Returns: List[Dict[str, Any]] — List of filter schema dicts (name, kind, ops, datasets, required, ...).

Method DatasetManager.set_filters

Define (or replace) common-field filters on this DatasetManager.

Validates each definition against registered datasets and stores it on this instance (no global state). Existing definitions with the same name are replaced.

set_filters(filter_definitions: List[Dict[str, Any]]) -> str

Parameter Type Default Description
filter_definitions List[Dict[str, Any]] List of filter definition dicts. Each must include "name" (str), "columns" (list of str), "kind" (categorical/numeric/temporal/text/spatial), and "ops" (list of operators). Optional: "required" (bool), "label" (str), "description" (str).

Returns: str — Confirmation string listing stored filter names.

Raises:

  • ValueError — When a spatial filter has no registered spatial profile.

Method DatasetManager.apply_filters

Apply a filter request recursively across all matching datasets.

Resolves each key in request against the stored filter catalog (self._filter_defs), then applies the condition to every registered dataset that contains the target column(s).

Execution strategy per source type:

  • In-memory DataFrames (InMemorySource or already materialized): filtered via the extended :meth:_apply_filter (pandas path).
  • SQL-backed sources (TableSource/QuerySlugSource): materialized first (fetching from the database if needed), then filtered via pandas. The :class:FilterCompiler SQL compile path is available for future in-database push-down; this orchestrator currently uses the materialize-then-filter strategy for reliability.
  • kind="spatial": delegates entirely to :meth:spatial_filter.

Datasets that lack the target column(s) are:

  • Silently skipped and recorded in result.skipped when definition.required is False (default).
  • Cause a ValueError naming the dataset when required is True.

apply_filters(request: Dict[str, Any], *, persist: bool = False) -> 'FilterResult'

Parameter Type Default Description
request Dict[str, Any] Mapping of filter name → value. A bare scalar becomes FilterCondition(op="eq", value=scalar); a bare list becomes FilterCondition(op="in", value=list); a FilterCondition or dict with {"op": ..., "value": ...} is used as-is.
persist bool False When True, the filtered DataFrame for each dataset is registered in this manager under the name <original>__filtered (with a collision guard). Default is False (ephemeral).

Returns: 'FilterResult' — class:FilterResult with applied and skipped lists.

Raises:

  • KeyError — When a request key does not match any stored definition.
  • ValueError — When a required=True filter targets a dataset that lacks the column(s).

Method DatasetManager.get_manifest

Return a manifest of all datasets that have a spatial profile.

Each entry carries the layer id, geodesic hint, and property columns for that dataset — the minimum the frontend needs to configure Leaflet layers and the LLM needs to understand which datasets are spatially queryable.

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

Returns: List[Dict[str, Any]] — List of dicts, one per spatially-profiled dataset::

[ { "dataset": "schools", "layer": "schools", "geodesic": True, "property_cols": ["name", "type"], }, ... ] Only datasets that (a) have a registered spatial profile AND (b) exist in this DatasetManager instance are included. Profiles for unknown datasets are skipped with a debug log.

Method DatasetManager.spatial_filter

Execute a spatial radius filter across one or more datasets.

This is a thin orchestration method — it does not contain any SQL or geometry math. All translation lives in :class:SpatialCompiler.

Flow:

  1. Resolve each dataset name via _resolve_name; validate that every dataset has a registered spatial profile (descriptive ValueError).
  2. Group datasets by (driver, connection) so co-located tables share one AsyncDB connection.
  3. asyncio.gather per group, propagating the current PermissionContext via _pctx_var so concurrent requests remain isolated.
  4. Build a per-dataset SpatialResult (FEAT-221 G4) with one SpatialLayerResult per dataset, preserving individual capping and geodesic flags. A back-compat as_feature_collection() helper is available for callers that still need the legacy merged shape.

spatial_filter(spec: 'SpatialFilterSpec', cap_per_dataset: int = 1000) -> 'SpatialResult'

Parameter Type Default Description
spec 'SpatialFilterSpec' Spatial filter request — point, radius, datasets. Backend-agnostic.
cap_per_dataset int 1000 Hard cap on features returned per dataset. Defaults to 1000. True count is always recorded in total_count.

Returns: 'SpatialResult' — A SpatialResult (versioned per-dataset grouping, FEAT-221 G4). Use result.as_feature_collection() to get the legacy merged shape.

Raises:

  • ValueError — If any dataset name in spec.datasets is not registered in this DatasetManager instance OR lacks a spatial profile.

Alias DatasetManagerConfig

Re-exported from parrot.tools.dataset_manager.config.DatasetManagerConfig.

Alias DatasetPolicyGuard

Re-exported from parrot.auth.dataset_guard.DatasetPolicyGuard.

Alias DatasourceSpec

Re-exported from parrot.tools.dataset_manager.config.DatasourceSpec.

Alias FileDatasource

Re-exported from parrot.tools.dataset_manager.config.FileDatasource.

Class FileEntry

A file loaded into DatasetManager (not a DataFrame).

Stores structural analysis and per-table markdown for files loaded via :meth:DatasetManager.load_file.

Parameter Type Default Description
name str
path Path
file_type str
markdown_content Dict[str, str]
structural_summary str
analysis Optional[Any] None
metadata Optional[Dict[str, Any]] None

Fields:

Field Type Default Description
name str
path Path
file_type str
markdown_content Dict[str, str]
structural_summary str
analysis Optional[Any] None
metadata Optional[Dict[str, Any]] None

Alias FilterDefinition

Re-exported from parrot.tools.dataset_manager.filtering.contracts.FilterDefinition.

Alias FilterResult

Re-exported from parrot.tools.dataset_manager.filtering.contracts.FilterResult.

Attribute GOVERNED_FRAME_SLOTS

Type: int

Alias PermissionContext

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

Alias REDIS_DATASET_URL

Re-exported from parrot.conf.REDIS_DATASET_URL.

Alias SpatialFilterSpec

Re-exported from parrot.tools.dataset_manager.spatial.contracts.SpatialFilterSpec.

Alias SpatialLayerResult

Re-exported from parrot.tools.dataset_manager.spatial.contracts.SpatialLayerResult.

Alias SpatialResult

Re-exported from parrot.tools.dataset_manager.spatial.contracts.SpatialResult.

Alias lazy_import

Re-exported from parrot._imports.lazy_import.

Attribute logger

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