Skip to content

API Reference parrot.tools.pythonrepl

github-actions[bot] edited this page Nov 5, 2026 · 4 revisions

parrot.tools.pythonrepl

View source

PythonREPLTool migrated to use AbstractTool framework.

Alias AbstractTool

Re-exported from parrot.tools.abstract.AbstractTool.

Class PythonREPLArgs

Arguments schema for PythonREPLTool.

Fields:

Field Type Default Description
code str Python code to execute in the REPL environment
debug bool False

Class PythonREPLTool

Python REPL Tool with pre-loaded data science libraries and enhanced capabilities.

Features:

  • Pre-loaded libraries: pandas (pd), numpy (np), numexpr (ne)
  • Lazy-loaded optional libraries: altair, plotly, folium
  • Report directory management
  • JSON serialization/deserialization for execution results

matplotlib and seaborn are NOT available (FEAT-423) — visualization flows through structured-chart / A2UI output modes, with altair as the sole fallback for complex edge cases. matplotlib/matplotlib.pyplot are in BLOCKED_IMPORTS.

Parameter Type Default Description
locals_dict Optional[Dict] None Local variables for the REPL
globals_dict Optional[Dict] None Global variables for the REPL
report_dir Optional[Path] None Directory for saving reports
setup_code Optional[str] None Custom setup code to run
sanitize_input_enabled bool True Whether to sanitize input
debug bool False
policy None PythonExecutionPolicy for the allowlist-first AST gate. Defaults to general_profile().
executor_max_workers int 4 Size of the dedicated thread pool used to run generated code (FEAT-380 Module 1 / AC1). A runaway loop then only exhausts this REPL-scoped pool instead of the framework's shared default executor. Kept for the palliative that shipped in Module 1; no longer on the code-execution path itself (Module 5 moves that to the worker process) but preserved so any caller still relying on the attribute keeps working.
worker_config None repl_worker.protocol.WorkerConfig — resource limits / lifecycle tuning for this instance's persistent worker process (FEAT-380 Module 5). Defaults to WorkerConfig() (lazily, on first use).
execution_mode Optional[str] None "worker" (default — persistent sandboxed worker process) or "inprocess" (escape hatch: generated code runs inside the host process on _repl_executor, the pre-FEAT-380 behaviour, with NO process isolation, rlimits or SIGKILL deadline). None reads the PYTHON_REPL_EXECUTION_MODE environment variable (fallback "worker"). See repl_worker/inprocess.py.
**kwargs {} Additional arguments for AbstractTool

Attributes:

Attribute Type Description
BLOCKED_IMPORTS set
BLOCKED_NAMES set
BLOCKED_ATTRIBUTES set
execution_mode str "worker" or "inprocess" — resolved once at construction.

Method PythonREPLTool.get_var

Read one namespace variable from this instance's worker (namespace API).

get_var(name: str) -> Any

Parameter Type Default Description
name str Variable name in the REPL namespace.

Returns: Any — The variable's current value.

Method PythonREPLTool.set_var

Write one namespace variable in this instance's worker (namespace API).

set_var(name: str, value: Any) -> None

Parameter Type Default Description
name str Variable name to bind in the REPL namespace.
value Any Value to assign.

Method PythonREPLTool.list_vars

List variable names currently in this instance's worker namespace.

list_vars() -> List[str]

Returns: List[str]

Method PythonREPLTool.snapshot

Return a serializable dump of this instance's worker namespace.

snapshot() -> Dict[str, Any]

Returns: Dict[str, Any]

Method PythonREPLTool.inject_dataframe

Inject a DataFrame into this instance's worker via Arrow IPC/shm (FEAT-380 Module 7).

inject_dataframe(name: str, df: Any) -> None

Parameter Type Default Description
name str Variable name to bind the DataFrame to in the REPL namespace.
df Any The pandas.DataFrame to inject.

Method PythonREPLTool.execute_sync

Execute Python code synchronously.

execute_sync(code: str, debug: bool = False) -> str

Parameter Type Default Description
code str Python code to execute
debug bool False Enable debug mode

Returns: str — Execution result as string

Method PythonREPLTool.get_environment_info

Get information about the current REPL environment.

get_environment_info() -> Dict[str, Any]

Returns: Dict[str, Any]

Method PythonREPLTool.reset_environment

Reset the REPL environment to its initial state.

FEAT-380 Module 5: resetting now means killing and replacing this instance's WORKER (where code actually executes) on its next use — the namespace is intentionally cleared, matching a fresh worker's empty namespace. This method's public signature stays synchronous, so it only flags the worker for replacement here; _execute()/the namespace API kill + lazily respawn it (this tool's existing "lazy start" pattern already works this way — see _get_worker_handle). The host's OWN instance still re-bootstraps below unchanged, since external call sites not yet ported to the namespace API (TASK-1944) still read self.locals/self.globals directly.

reset_environment() -> None

Method PythonREPLTool.save_execution_results

Save current execution results to a JSON file.

save_execution_results(filename: Optional[str] = None) -> Dict[str, Any]

Parameter Type Default Description
filename Optional[str] None Optional filename for the output file

Returns: Dict[str, Any] — Dictionary with file information

Method PythonREPLTool.load_execution_results

Load execution results from a JSON file.

load_execution_results(file_path: Union[str, Path]) -> Dict[str, Any]

Parameter Type Default Description
file_path Union[str, Path] Path to the JSON file

Returns: Dict[str, Any] — Dictionary with loading information

Method PythonREPLTool.safe_execution_context

Context manager for safe code execution that prevents crashes.

safe_execution_context()

Method PythonREPLTool.execute_code_safely

Execute code with maximum safety against crashes.

execute_code_safely(code: str, debug: bool = False) -> str

Parameter Type Default Description
code str
debug bool False

Returns: str

Function brace_escape

Escape curly braces in text for format strings.

brace_escape(text: str) -> str

Parameter Type Default Description
text str

Returns: str

Alias lazy_import

Re-exported from parrot._imports.lazy_import.

Alias redact_text

Re-exported from parrot.security.redaction.redact_text.

Function resolve_execution_mode

Resolve the REPL execution mode: explicit argument, else environment.

resolve_execution_mode(explicit: Optional[str] = None) -> str

Parameter Type Default Description
explicit Optional[str] None The execution_mode constructor argument. None reads PYTHON_REPL_EXECUTION_MODE from the environment / navconfig (fallback "worker"), so a deployment can flip every tool — including the ones agents such as PandasAgent build internally — without touching agent code.

Returns: str — "worker" (persistent sandboxed worker process, the default) or "inprocess" (pre-FEAT-380 behaviour: code runs inside the host process, see repl_worker/inprocess.py).

Raises:

  • ValueError — The value is not one of :data:_EXECUTION_MODES.

Function sanitize_input

Sanitize input to the python REPL. Remove whitespace, backtick & python (if llm mistakes python console as terminal)

sanitize_input(query: str) -> str

Parameter Type Default Description
query str The query to sanitize

Returns: str — The sanitized query

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