Skip to content

API Reference parrot.bots.data

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

parrot.bots.data

View source

PandasAgent. A specialized agent for data analysis using pandas DataFrames.

Alias AGENTS_DIR

Re-exported from parrot.conf.AGENTS_DIR.

Alias AIMessage

Re-exported from parrot.models.responses.AIMessage.

Alias AbstractTool

Re-exported from parrot.tools.AbstractTool.

Alias AgentResponse

Re-exported from parrot.models.responses.AgentResponse.

Alias BasicAgent

Re-exported from parrot.bots.agent.BasicAgent.

Alias DATAFRAME_CONTEXT_LAYER

Re-exported from parrot.bots.prompts.domain_layers.DATAFRAME_CONTEXT_LAYER.

Alias DATA_INSTRUCTIONS_LAYER

Re-exported from parrot.bots.prompts.domain_layers.DATA_INSTRUCTIONS_LAYER.

Attribute DEFAULT_OUTPUT_MODE_ROUTES

Type: Dict[str, List[str]]

Class DataRouteDecision

Structured decision returned by the lightweight DatasetManager router.

Fields:

Field Type Default Description
route DataToolRoute DataToolRoute.DATA_ANALYSIS 'conversational' for greetings, introductions, thanks, or general capability/meta questions answerable without tools; 'non_data_tools' for glossary, skill, or memory operations that do not touch datasets; 'data_analysis' for any question requiring dataset inspection, querying, calculations, forecasting, or charts.
reason str '' Short 1-sentence rationale for logging.

Class DataToolRoute

Per-turn tool-injection route decided by the PandasAgent dataset router.

Alias DatasetManager

Re-exported from parrot.tools.dataset_manager.DatasetManager.

Class DatasetResult

A single named dataset in a multi-dataset response.

Used when a query involves multiple datasources and PandasAgentResponse needs to return more than one result table.

Fields:

Field Type Default Description
name str Dataset name or alias
variable str Python variable name holding this DataFrame
data List[Dict[str, Any]] Records (list of row dicts)
shape Tuple[int, int] (rows, columns)
columns List[str] Column names

Alias GuardrailContext

Re-exported from parrot.bots.guardrails.base.GuardrailContext.

Alias GuardrailStage

Re-exported from parrot.bots.guardrails.base.GuardrailStage.

Alias IntentRouterConfig

Re-exported from parrot.registry.capabilities.models.IntentRouterConfig.

Alias IntentRouterMixin

Re-exported from parrot.bots.mixins.intent_router.IntentRouterMixin.

Alias OUTPUT_SYSTEM_PROMPT

Re-exported from parrot.bots.prompts.OUTPUT_SYSTEM_PROMPT.

Alias OutputMode

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

Alias OutputShape

Re-exported from parrot.registry.routing.route_labels.OutputShape.

Attribute PANDAS_INSTRUCTIONS_LAYER

Class PandasAgent

A specialized agent for data analysis using pandas DataFrames.

Features:

  • Multi-dataframe support
  • Redis caching for data persistence
  • Automatic EDA (Exploratory Data Analysis)
  • DataFrame metadata generation
  • Query source integration
  • File loading (CSV, Excel)
Parameter Type Default Description
name str 'Pandas Agent' Agent name
enable_scenarios bool False
tools List[AbstractTool] None Additional tools beyond default
system_prompt str None Custom system prompt
df Union[List[pd.DataFrame], Dict[str, Union[pd.DataFrame, pd.Series, Dict[str, Any]]], pd.DataFrame, pd.Series] None DataFrame(s) to analyze
query Union[List[str], dict] None QuerySource queries to execute
capabilities str None Agent capabilities description
generate_eda bool True Generate exploratory data analysis
cache_expiration int 24 Cache expiration in hours
temperature float 0.0
max_iterations Optional[int] None
output_routing bool False When True, activate the pre-LLM embedding-based output-mode router (FEAT-224) so the agent auto-selects STRUCTURED_CHART/TABLE/MAP from the user's phrasing. Opt-in because it lazy-loads a SentenceTransformer (embeddings extra) and encodes a phrase bank at configure() time.
output_routing_config Optional[IntentRouterConfig] None Optional :class:IntentRouterConfig to override the default bilingual phrase bank / thresholds. When provided, it takes precedence over the output_routing flag's default config (and must set enable_output_mode_routing=True to activate).
python_repl_execution_mode Optional[str] None Forwarded to the internal PythonPandasTool as its execution_mode — "worker" (default, persistent sandboxed worker process) or "inprocess" (escape hatch: generated code runs inside the host process, no process isolation/rlimits/SIGKILL deadline; see PythonREPLTool.__init__). None (the default) falls through to that tool's own resolution, which reads the PYTHON_REPL_EXECUTION_MODE environment variable (fallback "worker") — so a subclass or caller can pin a mode per-agent, per-instance, without touching the deployment environment.
python_repl_executor_max_workers Optional[int] None Forwarded to the internal PythonPandasTool as executor_max_workers. None (the default) auto-sizes the REPL thread pool to the WorkerPool capacity (max workers + prewarm), avoiding the "shared executor undersized" warning.
dataset_router bool False When True (or when the class attribute dataset_router is True), hold the REPL/Prophet/ToJson and DatasetManager tools out of the persistent tool registry and inject them per request only when the router classifies the turn as data analysis (FEAT-931).
dataset_router_model Optional[str] None Model used by the Tier 1 router call. None falls back to the client's lightweight model.
dataset_router_timeout Optional[float] None Seconds before the Tier 1 router call fails open to data_analysis. None uses the class attribute dataset_router_timeout (3.0 by default); any explicit value, 3.0 included, overrides it.
**kwargs {} Additional configuration

Attributes:

Attribute Type Description
dataset_router bool
dataset_router_model Optional[str]
dataset_router_timeout float
queries Union[List[str], dict]
dataframes Dict[str, pd.DataFrame] The active DataFrames the current call sees. Inside :meth:session_dataset_manager_scope these are the bound session DatasetManager's active frames; elsewhere the agent's own mirror, rebuilt by :meth:_sync_dataframes_from_dm. Concurrent requests on one shared agent never read each other's frames.
df_metadata Dict[str, Dict[str, Any]] Metadata for :attr:dataframes: built per read inside a session scope, else the agent's own mirror.

Method PandasAgent.session_dataset_manager_scope

Use dm as this request's DatasetManager without attaching it to the shared agent.

Every read of self._dataset_manager, self.dataframes and self.df_metadata in the current context (the per-request data tool bundle, the prompt catalog, Prophet, drained artifacts) reads dm until the block exits; other requests keep their own. The caller wires dm's change callbacks. Nothing on the shared agent is written while dm is bound, so exit only unbinds it, unless :meth:attach_dm replaced the agent's own DatasetManager meanwhile: then the agent-level state is synced from the new one.

session_dataset_manager_scope(dm: DatasetManager) -> Iterator[DatasetManager]

Parameter Type Default Description
dm DatasetManager The session-scoped DatasetManager for this request.

Returns: Iterator[DatasetManager]

Method PandasAgent.attach_dm

Attach a DatasetManager to this agent.

The DatasetManager provides the data catalog. Active datasets will be registered to PythonPandasTool when the agent is configured. This replaces the agent's own DatasetManager for every caller; to give one request a session DatasetManager on a shared agent, use :meth:session_dataset_manager_scope instead. Called inside such a scope, the sync is deferred to the scope's exit.

attach_dm(dm: DatasetManager) -> None

Parameter Type Default Description
dm DatasetManager DatasetManager instance

Method PandasAgent.create_system_prompt

Override to inject dataframe_schemas for the layer path.

create_system_prompt(**kwargs)

Parameter Type Default Description
**kwargs {}

Method PandasAgent.configure

Configure the PandasAgent.

configure(app: web.Application = None, queries: Union[List[str], dict] = None) -> None

Parameter Type Default Description
app web.Application None Optional aiohttp Application
queries Union[List[str], dict] None Optional query slugs to load data from

Method PandasAgent.invoke

Ask the agent a question about the data.

invoke(question: str, response_model: type[BaseModel] | None = None, **kwargs) -> AgentResponse

Parameter Type Default Description
question str Question to ask
response_model type[BaseModel] | None None
**kwargs {} Additional parameters

Returns: AgentResponse — AgentResponse with answer and metadata

Method PandasAgent.ask

Override ask() method to run the DataFrame analysis tool loop.

This method is specialized for PandasAgent and differs from AbstractBot.ask():

  • Uses tools (specifically PythonPandasTool) unless use_tools=False
  • Does NOT use vector search/knowledge base context
  • Returns AIMessage
  • Focuses on DataFrame analysis with the pre-loaded data

ask(question: str, session_id: Optional[str] = None, user_id: Optional[str] = None, use_conversation_history: bool = True, memory: Optional[Any] = None, ctx: Optional[Any] = None, structured_output: Optional[Any] = None, output_mode: Any = None, format_kwargs: dict = None, return_structured: bool = True, use_tools: bool = True, **kwargs) -> AIMessage

Parameter Type Default Description
question str The user's question about the data
session_id Optional[str] None Session identifier for conversation history
user_id Optional[str] None User identifier
use_conversation_history bool True Whether to use conversation history
memory Optional[Any] None Optional memory handler
ctx Optional[Any] None Request context
structured_output Optional[Any] None Structured output configuration or model
output_mode Any None Output formatting mode
format_kwargs dict None Additional kwargs for formatter
return_structured bool True Whether to return a default structured output (PandasAgentResponse)
use_tools bool True Whether to offer the agent's tools to the LLM. False sends no function declarations at all (no ToolManager tools, no client-registered tools) — for prompts that already carry every figure and want prose/tables back.
**kwargs {} Additional arguments (temperature, max_tokens, etc.)

Returns: AIMessage — AIMessage with the analysis result

Method PandasAgent.add_dataframe

Add a new DataFrame to the agent's context via DatasetManager.

add_dataframe(name: str, df: pd.DataFrame, metadata: Optional[Dict[str, Any]] = None, regenerate_guide: bool = True) -> str

Parameter Type Default Description
name str Name for the DataFrame
df pd.DataFrame The pandas DataFrame to add
metadata Optional[Dict[str, Any]] None Optional column metadata dictionary
regenerate_guide bool True Deprecated (handled by DatasetManager)

Returns: str — Success message

Method PandasAgent.add_query

Register a new QuerySource slug and load its resulting DataFrame.

add_query(query: str) -> Dict[str, pd.DataFrame]

Parameter Type Default Description
query str

Returns: Dict[str, pd.DataFrame]

Method PandasAgent.refresh_data

Re-run the configured queries and refresh metadata/tool state.

refresh_data(cache_expiration: int = None, **kwargs) -> Dict[str, pd.DataFrame]

Parameter Type Default Description
cache_expiration int None
**kwargs {}

Returns: Dict[str, pd.DataFrame]

Method PandasAgent.delete_dataframe

Remove a DataFrame from the agent's context via DatasetManager.

delete_dataframe(name: str, regenerate_guide: bool = True) -> str

Parameter Type Default Description
name str Name of the DataFrame to remove
regenerate_guide bool True Deprecated (handled by DatasetManager)

Returns: str — Success message

Method PandasAgent.session_data_tool_scope

Use pandas_tool as this request's REPL without registering it anywhere (router-enabled agents).

session_data_tool_scope(pandas_tool: Optional[PythonPandasTool]) -> Iterator[None]

Parameter Type Default Description
pandas_tool Optional[PythonPandasTool]

Returns: Iterator[None]

Method PandasAgent.list_dataframes

Get a list of all DataFrames loaded in the agent's context.

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

Returns: Dict[str, Dict[str, Any]] — Dictionary mapping standardized keys (df1, df2, etc.) to DataFrame info: - original_name: The original name of the DataFrame - standardized_key: The standardized key (df1, df2, etc.) - shape: Tuple of (rows, columns) - columns: List of column names - memory_usage_mb: Memory usage in megabytes - null_count: Total number of null values

Method PandasAgent.default_backstory

Return default backstory for the agent.

default_backstory() -> str

Returns: str

Method PandasAgent.load_from_files

Load DataFrames from CSV or Excel files.

load_from_files(files: Union[str, Path, List[Union[str, Path]]], **kwargs) -> Dict[str, pd.DataFrame]

Parameter Type Default Description
files Union[str, Path, List[Union[str, Path]]] File path(s) to load
**kwargs {} Additional pandas read options

Returns: Dict[str, pd.DataFrame] — Dictionary of DataFrames

Class PandasAgentResponse

Structured response for PandasAgent operations.

Fields:

Field Type Default Description
explanation str Clear, text-based explanation of the analysis performed. Include insights, findings, and interpretation of the data. Do NOT embed the full result table here — the table is delivered separately via 'data'/'data_variable'. A short highlight of a few rows is acceptable when it aids the narrative.
data Optional[PandasTable] None Set to null. ALWAYS use data_variable instead — the system retrieves ALL rows automatically. Only populate this field when the result is a tiny inline table (≤5 rows) not backed by a variable.\nFormat when used: {'columns': [...], 'rows': [[...], [...], ...]}.\nCRITICAL: All numeric values in rows MUST be raw numbers. NEVER include currency symbols ($, €, £), percent signs (%), thousands separators (commas), or any other formatting. Return 764539.74 NOT '$764,539.74'. Return 85.3 NOT '85.3%'.
data_variable Optional[str] None PREFERRED way to return tabular results: the exact variable name your executed Python code assigned the result DataFrame to (e.g. 'result_df'). ALWAYS set this when your code produced a result DataFrame this turn, regardless of its size — the system retrieves the full DataFrame from memory automatically. Only declare variables your executed code actually created. Use JSON null (not the string 'None' or 'null') when no variable applies.
data_variables Optional[List[str]] None List of variable names holding result DataFrames when the response involves multiple datasets. Each variable is resolved and included as a separate entry in the response data. Use this instead of 'data_variable' when 2 or more datasets are involved. Use JSON null when no variables apply; omit null entries from the list.
code Optional[Union[str, Dict[str, Any]]] None The Python code used for analysis OR the Code generated under request (e.g. JSON definition for a Altair/Vega Chart).

Method PandasAgentResponse.normalize_data_variable

Normalize textual nulls without changing actual variable references.

normalize_data_variable(value: Any) -> Any

Parameter Type Default Description
value Any Raw variable reference from the structured response.

Returns: Any — None for empty or textual null values, otherwise the original value.

Method PandasAgentResponse.normalize_data_variables

Remove null references while preserving order and type validation.

normalize_data_variables(value: Any) -> Any

Parameter Type Default Description
value Any Raw variable list from the structured response.

Returns: Any — References without null entries, or None when none remain. Unsupported input types pass through to Pydantic validation.

Method PandasAgentResponse.parse_data

Handle cases where LLM returns stringified JSON for data.

parse_data(v)

Parameter Type Default Description
v

Method PandasAgentResponse.to_dataframe

to_dataframe() -> Optional[pd.DataFrame]

Returns: Optional[pd.DataFrame]

Class PandasMetadata

Metadata information for PandasAgent responses.

Fields:

Field Type Default Description
shape Optional[List[int]] None (rows, columns) of the DataFrame
columns Optional[List[str]] None List of DataFrame column names
summary_stats Optional[List[SummaryStat]] None Summary statistics as a list of metric/value pairs. Example: [{'metric': 'mean', 'value': 12.3}, ...]

Alias PandasTable

Re-exported from parrot.models.tables.PandasTable.

Alias PromptBuilder

Re-exported from parrot.bots.prompts.builder.PromptBuilder.

Alias PythonPandasTool

Re-exported from parrot.tools.pythonpandas.PythonPandasTool.

Alias RequestToolPreparation

Re-exported from parrot.bots.base.RequestToolPreparation.

Alias STATIC_DIR

Re-exported from parrot.conf.STATIC_DIR.

Alias STRICT_GROUNDING_LAYER

Re-exported from parrot.bots.prompts.domain_layers.STRICT_GROUNDING_LAYER.

Alias Scalar

Re-exported from parrot.models.tables.Scalar.

Alias StructuredChartConfig

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

Alias StructuredOutputConfig

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

Class SummaryStat

Single summary statistic for a DataFrame column.

Fields:

Field Type Default Description
metric str Name of the metric, e.g. 'mean', 'max', 'min', 'std'
value float Numeric value of this metric

Alias TOOLLESS_DATA_GROUNDING_LAYER

Re-exported from parrot.bots.prompts.domain_layers.TOOLLESS_DATA_GROUNDING_LAYER.

Alias ToJsonTool

Re-exported from parrot.tools.json_tool.ToJsonTool.

Alias attach_structured_artifact

Re-exported from parrot.outputs.a2ui.artifacts.attach_structured_artifact.

Alias bind_memory_exposure

Re-exported from parrot.memory.agent_memory.runtime.bind_memory_exposure.

Alias bind_memory_scope

Re-exported from parrot.memory.agent_memory.runtime.bind_memory_scope.

Alias build_component_prompt

Re-exported from parrot.outputs.a2ui.inline.prompt.build_component_prompt.

Alias component_model

Re-exported from parrot.outputs.a2ui.catalog._model.component_model.

Alias current_memory_exposure

Re-exported from parrot.memory.agent_memory.runtime.current_memory_exposure.

Alias current_memory_key_id

Re-exported from parrot.observability.context.current_memory_key_id.

Alias current_session_id

Re-exported from parrot.observability.context.current_session_id.

Alias current_user_id

Re-exported from parrot.observability.context.current_user_id.

Alias emit_inline_component

Re-exported from parrot.outputs.a2ui.inline.emitter.emit_inline_component.

Alias enter_active_skill_scope

Re-exported from parrot.skills.tenancy.enter_active_skill_scope.

Alias exit_active_skill_scope

Re-exported from parrot.skills.tenancy.exit_active_skill_scope.

Alias finalize_a2ui_response

Re-exported from parrot.outputs.a2ui.emission.finalize_a2ui_response.

Alias get_component_hint

Re-exported from parrot.registry.routing.route_labels.get_component_hint.

Alias is_inline_component

Re-exported from parrot.registry.routing.route_labels.is_inline_component.

Attribute logger

Alias reset_memory_exposure

Re-exported from parrot.memory.agent_memory.runtime.reset_memory_exposure.

Alias reset_memory_scope

Re-exported from parrot.memory.agent_memory.runtime.reset_memory_scope.

Alias resolve_route_banks

Re-exported from parrot.registry.routing.route_bank.resolve_route_banks.

Alias secure_path

Re-exported from parrot.utils.paths.secure_path.

Alias set_output_shape

Re-exported from parrot.registry.routing.route_labels.set_output_shape.

Alias with_call_identity

Re-exported from parrot.bots.base.with_call_identity.

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