Skip to content

API Reference parrot_tools.whatif

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

parrot_tools.whatif

View source

What-If Scenario Analysis Tool for AI-Parrot Supports derived metrics, constraints, and optimization

Alias AbstractTool

Re-exported from parrot_tools.abstract.AbstractTool.

Class Action

Defines a possible action

Parameter Type Default Description
name str
column str
operation str
value any
cost float 0.0
affects_derived bool False
alternative_group Optional[str] None

Fields:

Field Type Default Description
name str
column str
operation str
value any
cost float 0.0
affects_derived bool False
alternative_group Optional[str] None

Class Constraint

Defines a constraint

Parameter Type Default Description
metric str
type ConstraintType
value float
reference_metric Optional[str] None

Fields:

Field Type Default Description
metric str
type ConstraintType
value float
reference_metric Optional[str] None

Class ConstraintType

Type of constraint

Class DerivedMetric

Calculated/derived metric

Fields:

Field Type Default Description
name str Name of derived metric (e.g., 'revenue_per_visit')
formula str Formula as string (e.g., 'revenue / visits')
description Optional[str] Description of what it represents

Class MetricsCalculator

Calculates derived metrics on DataFrames

Attributes:

Attribute Type Description
formulas Dict[str, str]
descriptions Dict[str, str]

Method MetricsCalculator.register_metric

Register a derived metric

register_metric(name: str, formula: str, description: str = '')

Parameter Type Default Description
name str
formula str
description str ''

Method MetricsCalculator.calculate

Calculate a derived metric

calculate(df: pd.DataFrame, metric_name: str) -> pd.Series

Parameter Type Default Description
df pd.DataFrame
metric_name str

Returns: pd.Series

Method MetricsCalculator.add_to_dataframe

Add all derived metrics to DataFrame

add_to_dataframe(df: pd.DataFrame) -> pd.DataFrame

Parameter Type Default Description
df pd.DataFrame

Returns: pd.DataFrame

Method MetricsCalculator.get_base_value

Get total value of a metric (derived or not)

get_base_value(df: pd.DataFrame, metric_name: str) -> float

Parameter Type Default Description
df pd.DataFrame
metric_name str

Returns: float

Class Objective

Defines an optimization objective

Parameter Type Default Description
metric str
type ObjectiveType
target_value Optional[float] None
weight float 1.0

Fields:

Field Type Default Description
metric str
type ObjectiveType
target_value Optional[float] None
weight float 1.0

Class ObjectiveType

Type of optimization objective

Class ScenarioOptimizer

Optimizer with support for derived metrics

Parameter Type Default Description
base_df pd.DataFrame
calculator MetricsCalculator

Method ScenarioOptimizer.evaluate_scenario

Evaluate metrics of a scenario (including derived)

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

Parameter Type Default Description
df pd.DataFrame

Returns: Dict[str, Dict]

Method ScenarioOptimizer.check_constraints

Check if scenario meets constraints

check_constraints(df: pd.DataFrame, constraints: List[Constraint]) -> Tuple[bool, List[str]]

Parameter Type Default Description
df pd.DataFrame
constraints List[Constraint]

Returns: Tuple[bool, List[str]]

Method ScenarioOptimizer.objective_function

Calculate objective function value

objective_function(df: pd.DataFrame, objectives: List[Objective]) -> float

Parameter Type Default Description
df pd.DataFrame
objectives List[Objective]

Returns: float

Class ScenarioResult

Result of an optimized scenario

Parameter Type Default Description
scenario_name str
base_df pd.DataFrame
result_df pd.DataFrame
actions List[Action]
optimizer ScenarioOptimizer
calculator MetricsCalculator

Fields:

Field Type Default Description
scenario_name str
base_df pd.DataFrame
result_df pd.DataFrame
actions List[Action]
optimizer ScenarioOptimizer
calculator MetricsCalculator

Method ScenarioResult.compare

Compare scenario with baseline

compare() -> Dict

Returns: Dict

Method ScenarioResult.visualize

Generate visual summary of the scenario

visualize() -> str

Returns: str

Alias ToolResult

Re-exported from parrot_tools.abstract.ToolResult.

Attribute WHATIF_SYSTEM_PROMPT

Class WhatIfAction

Possible action to take

Fields:

Field Type Default Description
type str Type: close_region, exclude_values, adjust_metric, set_value, scale_proportional
target str
parameters Annotated[Dict, BeforeValidator(validate_dict_or_json)]

Class WhatIfConstraint

Constraint for scenario

Fields:

Field Type Default Description
type str Type: max_change, min_value, max_value, or ratio
metric str
value float
reference_metric Optional[str] None

Class WhatIfDSL

Domain Specific Language for What-If analysis with optimization

Parameter Type Default Description
df pd.DataFrame
name str 'scenario'

Attributes:

Attribute Type Description
objectives List[Objective]
constraints List[Constraint]
possible_actions List[Action]
applied_actions List[Action]

Method WhatIfDSL.register_derived_metric

Register a derived metric

register_derived_metric(name: str, formula: str, description: str = '')

Parameter Type Default Description
name str
formula str
description str ''

Method WhatIfDSL.initialize_optimizer

Initialize optimizer after registering metrics

initialize_optimizer()

Method WhatIfDSL.minimize

Minimize a metric

minimize(metric: str, weight: float = 1.0) -> WhatIfDSL

Parameter Type Default Description
metric str
weight float 1.0

Returns: WhatIfDSL

Method WhatIfDSL.maximize

Maximize a metric

maximize(metric: str, weight: float = 1.0) -> WhatIfDSL

Parameter Type Default Description
metric str
weight float 1.0

Returns: WhatIfDSL

Method WhatIfDSL.target

Reach a target value

target(metric: str, value: float, weight: float = 1.0) -> WhatIfDSL

Parameter Type Default Description
metric str
value float
weight float 1.0

Returns: WhatIfDSL

Method WhatIfDSL.constrain_change

Constraint: metric cannot change more than X%

constrain_change(metric: str, max_pct: float) -> WhatIfDSL

Parameter Type Default Description
metric str
max_pct float

Returns: WhatIfDSL

Method WhatIfDSL.constrain_min

Constraint: metric must stay above X

constrain_min(metric: str, min_value: float) -> WhatIfDSL

Parameter Type Default Description
metric str
min_value float

Returns: WhatIfDSL

Method WhatIfDSL.constrain_max

Constraint: metric must stay below X

constrain_max(metric: str, max_value: float) -> WhatIfDSL

Parameter Type Default Description
metric str
max_value float

Returns: WhatIfDSL

Method WhatIfDSL.constrain_ratio

Constraint: ratio between two metrics

constrain_ratio(metric: str, reference: str, max_ratio: float) -> WhatIfDSL

Parameter Type Default Description
metric str
reference str
max_ratio float

Returns: WhatIfDSL

Method WhatIfDSL.can_close_regions

Define that regions can be closed

can_close_regions(regions: Optional[List[str]] = None) -> WhatIfDSL

Parameter Type Default Description
regions Optional[List[str]] None

Returns: WhatIfDSL

Method WhatIfDSL.can_exclude_values

Define that specific values can be excluded from a column (generic version of can_close_regions)

can_exclude_values(column: str, values: Optional[List[str]] = None) -> WhatIfDSL

Parameter Type Default Description
column str
values Optional[List[str]] None

Returns: WhatIfDSL

Method WhatIfDSL.can_adjust_metric

Define that a metric can be adjusted.

can_adjust_metric(metric: str, min_pct: float = -50, max_pct: float = 50, group_by: Optional[str] = None) -> WhatIfDSL

Parameter Type Default Description
metric str Metric to adjust
min_pct float -50 Minimum % change
max_pct float 50 Maximum % change
group_by Optional[str] None Optional column to group by (e.g. 'region' or 'Project')

Returns: WhatIfDSL

Method WhatIfDSL.can_scale_proportional

Allow scaling a base metric and adjust others proportionally.

Example: Increase 'visits' and have 'revenue' and 'expenses' scale according to revenue_per_visit and expenses_per_visit.

can_scale_proportional(base_column: str, affected_columns: List[str], min_pct: float = -50, max_pct: float = 100, group_by: Optional[str] = None) -> WhatIfDSL

Parameter Type Default Description
base_column str Base column to scale (e.g., 'visits')
affected_columns List[str] Columns that adjust proportionally (e.g., ['revenue', 'expenses'])
min_pct float -50 Minimum % change
max_pct float 100 Maximum % change
group_by Optional[str] None Optional column to group by

Returns: WhatIfDSL

Method WhatIfDSL.can_scale_entity

Allow scaling specific entities (rows) by a percentage.

Example: Scale Project 'Belkin' Revenue and Expenses by -50% This creates actions that filter by entity_column and scale target_columns.

can_scale_entity(entity_column: str, target_columns: List[str], entities: Optional[List[str]] = None, min_pct: float = -100, max_pct: float = 100) -> WhatIfDSL

Parameter Type Default Description
entity_column str Column to filter by (e.g., 'Project', 'region')
target_columns List[str] Columns to scale (e.g., ['Revenue', 'Expenses'])
entities Optional[List[str]] None Specific entities to allow scaling. If None, uses all unique values.
min_pct float -100 Minimum % change (e.g., -50 for "reduce to 50%")
max_pct float 100 Maximum % change

Returns: WhatIfDSL

Method WhatIfDSL.solve

Find best combination of actions that meets constraints.

solve(max_actions: int = 5, algorithm: str = 'greedy') -> ScenarioResult

Parameter Type Default Description
max_actions int 5 Maximum number of actions to take
algorithm str 'greedy' 'greedy' or 'genetic'

Returns: ScenarioResult

Class WhatIfInput

Input schema for WhatIfTool

Fields:

Field Type Default Description
scenario_description str
df_name Optional[str] None
objectives List[WhatIfObjective]
constraints List[WhatIfConstraint]
possible_actions List[WhatIfAction]
derived_metrics List[DerivedMetric] Calculated metrics from existing columns
max_actions int 5
algorithm str 'greedy'

Class WhatIfObjective

Objective for scenario optimization

Fields:

Field Type Default Description
type str Type: minimize, maximize, or target
metric str Column/metric name (can be derived)
target_value Optional[float] None
weight float 1.0

Class WhatIfTool

What-If Analysis Tool with support for derived metrics and optimization.

Allows LLM to execute hypothetical scenarios on DataFrames, optimize metrics under constraints, and compare results.

Attributes:

Attribute Type Description
args_schema Type[BaseModel]
scenarios_cache Dict[str, ScenarioResult]

Method WhatIfTool.set_parent_agent

Set reference to parent PandasAgent

set_parent_agent(agent)

Parameter Type Default Description
agent

Method WhatIfTool.get_input_schema

get_input_schema() -> type[BaseModel]

Returns: type[BaseModel]

Function integrate_whatif_tool

Integrate WhatIfTool into an existing PandasAgent.

integrate_whatif_tool(agent) -> WhatIfTool

Parameter Type Default Description
agent Instance of PandasAgent

Returns: WhatIfTool — The WhatIfTool instance (for reference)

Function validate_dict_or_json

Validate that value is a dict, or parse it from JSON string

validate_dict_or_json(v: Any) -> Dict

Parameter Type Default Description
v Any

Returns: Dict

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