Skip to content

API Reference parrot.tools.abstract

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

parrot.tools.abstract

View source

Abstract Tool base class for all function-calling tools.in ai-parrot framework.

Class AbstractTool

Abstract base class for all tools in the ai-parrot framework.

This class provides a unified interface for tools that can be used by both conversational bots and agents. It includes common functionality like:

  • Name and description management
  • JSON schema generation
  • File path management
  • Logging and error handling
  • Async/sync execution support
  • Lifecycle event emission (FEAT-176)
Parameter Type Default Description
name Optional[str] None Tool name (defaults to class name)
description Optional[str] None Tool description
output_dir Optional[Union[str, Path]] None Directory for output files (if tool generates files)
base_url Optional[str] None Base URL for serving static files
static_dir Optional[Union[str, Path]] None Static directory path
routing_meta Optional[Dict] None Optional routing hints dict for CapabilityRegistry. Supported keys: "description", "not_for".
executor Optional[AbstractToolExecutor] None Optional :class:AbstractToolExecutor that runs the tool off-process (Kubernetes pod, Qworker, etc.). When None (the default), the tool executes in-process — identical to the legacy behaviour.
webhook_callback_url Optional[str] None When set, the executor returns a ToolResult(status="pending") immediately and the final result arrives at this URL out-of-band. Only honoured by executors that support async delivery.
remote_timeout_seconds int 300 Max wall-clock seconds the executor waits for the remote runtime to return. Ignored when executor is None.
**kwargs {} Additional configuration

Attributes:

Attribute Type Description
args_schema Type[BaseModel]
return_direct bool
credential_provider Optional[str]
enable_redaction bool
auto_open bool
a2ui_requires_user_activation bool
a2ui_hidden bool
delegate_safe bool
delegate_description Optional[str]
tenant_bound bool
access Optional[str]
server_managed_params Dict[str, Any]
studio_hidden_args frozenset Arguments the host's store-only mode (:mod:parrot.tools.exports_mode) removes from the LLM schema and drops from a call. Empty = the tool is not affected; with the mode off nothing here has any effect.
routing_meta Dict
executor Optional[AbstractToolExecutor]
webhook_callback_url Optional[str]
remote_timeout_seconds int
name str
description str

Method AbstractTool.clone

Create a new instance of this tool with the same configuration.

This method creates a new instance of the tool class with all the initialization parameters that were passed to the current instance. Subclasses can override _get_clone_kwargs() to customize which parameters are cloned and which are not.

clone()

Method AbstractTool.get_schema

Get the JSON schema for this tool.

get_schema() -> Dict[str, Any]

Returns: Dict[str, Any] — JSON schema dictionary compatible with LLM tool registration

Method AbstractTool.get_tool_schema

Get the JSON schema for the tool's arguments. Alias for get_schema() for backward compatibility.

get_tool_schema() -> Dict[str, Any]

Returns: Dict[str, Any] — Dictionary containing the JSON schema

Method AbstractTool.validate_args

Validate arguments using the tool's schema.

validate_args(**kwargs) -> BaseModel

Parameter Type Default Description
**kwargs {} Arguments to validate

Returns: BaseModel — Validated arguments as Pydantic model instance

Method AbstractTool.execute

Execute the tool with error handling and result standardization.

TODO: Use the Global Registry to share data between tools.

execute(*args, **kwargs) -> ToolResult

Parameter Type Default Description
*args () Positional arguments for the tool.
**kwargs {} Tool arguments. Special kwargs are: - _permission_context: PermissionContext for Layer 2 enforcement - _resolver: AbstractPermissionResolver for permission checks - _a2ui_surface_state: The A2UI SurfaceState for the turn that triggered this call, if any (FEAT-469 spec §3 Module 8). When given, applied to the per-call _A2UI_SURFACE_STATE_VAR ContextVar for the duration of this call; otherwise the ambient value (set by AbstractBot.ask()) is used as-is. A tool's _execute() reads it via current_a2ui_surface_state(). Never forwarded to the LLM.

Returns: ToolResult — Standardized ToolResult. Returns status='forbidden' if permission denied.

Method AbstractTool.run

Public alias for executing the tool directly without the ToolResult wrapper. Provides a direct way to get raw results instead of calling _execute().

run(*args, **kwargs) -> Any

Parameter Type Default Description
*args ()
**kwargs {}

Returns: Any

Method AbstractTool.to_static_url

Convert an absolute file path to a static URL.

to_static_url(file_path: Union[str, Path]) -> str

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

Returns: str — URL-based path for serving the static file

Method AbstractTool.relative_url

Convert an absolute URL to a relative URL based on the base URL.

relative_url(url: str) -> str

Parameter Type Default Description
url str Absolute URL to convert

Returns: str — Relative URL based on the base URL

Method AbstractTool.generate_filename

Generate a unique filename with optional timestamp.

generate_filename(prefix: str = 'output', extension: str = '', include_timestamp: bool = True) -> str

Parameter Type Default Description
prefix str 'output' File prefix
extension str '' File extension (with or without dot)
include_timestamp bool True Whether to include timestamp

Returns: str — Generated filename

Method AbstractTool.validate_output_path

Validate and ensure the output path is within allowed directories.

validate_output_path(file_path: Union[str, Path]) -> Path

Parameter Type Default Description
file_path Union[str, Path] Path to validate

Returns: Path — Validated Path object

Raises:

  • ValueError — If path is outside allowed directories

Class AbstractToolArgsSchema

Base schema for tool arguments.

Subclasses can list field names in _context_fields that represent runtime context injected by the framework (e.g. user_id, session_id). These fields are excluded from the JSON schema sent to the LLM so the model is never asked to provide them. The framework injects them before validation at execution time.

Alias AbstractToolExecutor

Re-exported from parrot.tools.executors.abstract.AbstractToolExecutor.

Alias AfterToolCallEvent

Re-exported from parrot.core.events.lifecycle.events.AfterToolCallEvent.

Alias BASE_STATIC_URL

Re-exported from parrot.conf.BASE_STATIC_URL.

Alias BeforeToolCallEvent

Re-exported from parrot.core.events.lifecycle.events.BeforeToolCallEvent.

Alias CredentialBroker

Re-exported from parrot.auth.broker.CredentialBroker.

Alias EventEmitterMixin

Re-exported from parrot.core.events.lifecycle.EventEmitterMixin.

Alias OUTPUT_DIR

Re-exported from parrot.conf.OUTPUT_DIR.

Alias STATIC_DIR

Re-exported from parrot.conf.STATIC_DIR.

Alias ToolCallFailedEvent

Re-exported from parrot.core.events.lifecycle.events.ToolCallFailedEvent.

Class ToolExecutionRoute

Where one tool call runs: the remote executor and the envelope settings it receives.

Attributes:

Attribute Type Description
executor AbstractToolExecutor The executor the call is handed to.
remote_timeout_seconds int The envelope's timeout_seconds.
webhook_callback_url Optional[str] The envelope's webhook_callback_url, or None.

Class ToolOutputGuards

TOOL_OUTPUT guard settings one ToolManager dispatch applies to a tool's result.

Attributes:

Attribute Type Description
enable_redaction bool Whether the legacy secret/PII redaction opt-in is on for this call.
pipeline Optional[Any] The owning bot's TOOL_OUTPUT GuardrailPipeline, or None (the default SecretsGuardrail fallback applies).

Class ToolResult

Standardized tool result format.

Fields:

Field Type Default Description
success bool True Indicates if the tool executed successfully
status str 'success' Status of the operation
result Any The actual result of the tool operation
error Optional[str] None Error message if any
metadata Dict[str, Any] Additional metadata
timestamp str
files Optional[list] List of file paths generated by the tool
images Optional[list] List of image paths generated by the tool
voice_text Optional[str] None Text optimized for speech
display_data Optional[Dict[str, Any]] None Visual content to display

Attributes:

Attribute Type Description
spoken_content str Returns content for voice synthesis.
has_display_content bool Check if there's visual content to display.

Alias TraceContext

Re-exported from parrot.core.events.lifecycle.TraceContext.

Function current_a2ui_surface_state

Return the per-call A2UI SurfaceState for this turn, or None.

Tools can call this inside _execute() to read the SurfaceState (FEAT-469 spec §3 Module 8) associated with the turn that triggered this call, set either by AbstractBot.ask(a2ui_surface_state=...) (ambient, the common case) or by an explicit execute(_a2ui_surface_state=...) kwarg (direct/test callers). Reads a ContextVar — safe under concurrent invocations of the same shared tool instance, unlike an instance attribute.

current_a2ui_surface_state() -> Optional[Any]

Returns: Optional[Any] — The resolved SurfaceState, or None outside an A2UI-triggered turn.

Function current_credential

Return the per-call credential injected by the broker, or None.

Tools that declare credential_provider can call this inside _execute() to obtain the resolved per-user credential material. The value is set by the tool-loop seam (FEAT-264) just before _execute() is called and reset in the finally block.

current_credential() -> Optional[Any]

Returns: Optional[Any] — The resolved credential (token, API-key dict, …) or None if not in a credentialed execution context.

Function current_tool_output_guards

Return the dispatching manager's TOOL_OUTPUT guards for the running call.

current_tool_output_guards() -> Optional[ToolOutputGuards]

Returns: Optional[ToolOutputGuards] — The guards bound by ToolManager for the current tool.execute(), or None outside a manager dispatch.

Alias current_turn_tracker

Re-exported from parrot.auth.retry_safety.current_turn_tracker.

Alias gates

Re-exported from parrot.tools.execution_gates.

Attribute logger

Function tool_execution_route_scope

Bind a dispatch's route decision for tool around the enclosed tool.execute().

Enter and exit in the same task (ToolManager._call_tool_execute() wraps the awaited tool.execute()); the previous binding is restored with the set() token, so a nested dispatch through another manager restores the outer one on exit. Only tool itself reads the binding (:meth:AbstractTool._execution_route), and only while the dispatch runs: on exit the binding is deactivated, so a task spawned inside the dispatch that calls tool afterwards uses its registration route.

tool_execution_route_scope(tool: AbstractTool, route: Optional[ToolExecutionRoute]) -> Generator[Optional[ToolExecutionRoute], None, None]

Parameter Type Default Description
tool AbstractTool The tool instance this dispatch runs.
route Optional[ToolExecutionRoute] The dispatching manager's route, or None to run in-process.

Returns: Generator[Optional[ToolExecutionRoute], None, None]

Function tool_output_guards_scope

Bind guards for the enclosed tool.execute() call.

Enter and exit in the same task (ToolManager._call_tool_execute() wraps the awaited tool.execute()); the previous value is restored with the set() token, so a nested dispatch through another manager restores the outer manager's guards on exit.

tool_output_guards_scope(guards: ToolOutputGuards) -> Generator[ToolOutputGuards, None, None]

Parameter Type Default Description
guards ToolOutputGuards The dispatching manager's guards for this call.

Returns: Generator[ToolOutputGuards, None, None]

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