Skip to content

API Reference parrot.autonomous.orchestrator

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

parrot.autonomous.orchestrator

View source

Autonomy Orchestrator for AI-Parrot.

Unified orchestration layer that manages autonomous execution of:

  • Individual Agents
  • AgentCrews (sequential, parallel, flow, loop modes)
  • AgentFlows (DAG-based workflows)

Supports multiple trigger modes:

  • Scheduled (APScheduler)
  • Redis Jobs (dynamic injection)
  • Event Bus (pub/sub)
  • Webhooks (external triggers)

Alias AbstractBot

Re-exported from parrot.bots.abstract.AbstractBot.

Alias AgentCrew

Re-exported from parrot.bots.orchestration.AgentCrew.

Alias AgentRegistry

Re-exported from parrot.registry.AgentRegistry.

Class AutonomousOrchestrator

Unified orchestrator for autonomous agent and crew execution.

Provides a single interface to:
- Execute individual agents
- Execute AgentCrews in any mode (sequential, parallel, flow, loop)
- Trigger executions via multiple channels (schedule, events, webhooks, jobs)

Example:
        orchestrator = AutonomousOrchestrator(
            bot_manager=bot_manager,
            redis_url="redis://localhost:6379"
        )
        await orchestrator.start()
        
        # Execute a single agent
        result = await orchestrator.execute_agent("ResearchAgent", "Find info about X")
        
        # Execute a crew
        result = await orchestrator.execute_crew(
            "research_team",
            task="Analyze market trends",
            mode="flow"
        )
        
        # Inject a job for async execution
        job_id = await orchestrator.inject_job(
            target_type="crew",
            target_id="writing_team", 
            task="Write a blog post about AI"
        )
Parameter Type Default Description
bot_manager Optional['BotManager'] None BotManager instance (manages crews and bots)
agent_registry Optional['AgentRegistry'] None AgentRegistry instance (manages individual agents)
scheduler_manager Optional['SchedulerManager'] None Optional SchedulerManager for scheduled execution
redis_url Optional[str] None Redis URL for job injection and distributed events
use_event_bus bool True Enable event bus for pub/sub triggers
use_webhooks bool True Enable webhook listener for external triggers
default_user_id str 'autonomy_system' Default user ID for executions
default_session_prefix str 'auto_' Prefix for auto-generated session IDs

Attributes:

Attribute Type Description
event_bus Optional[EventBus]
job_injector Optional[RedisJobInjector]
webhook_listener Optional[WebhookListener]
hook_manager HookManager

Method AutonomousOrchestrator.start

Start all autonomy components.

start(ledger: 'Optional[EventLedger]' = None, *, resume_on_start: bool = False) -> None

Parameter Type Default Description
ledger 'Optional[EventLedger]' None Optional EventLedger instance. When provided alongside resume_on_start=True, the orchestrator calls self.resume(ledger) after all components are up to re-enqueue incomplete executions from the previous session. Callers that do not pass ledger are unaffected — this change is fully backward-compatible. (FEAT-212)
resume_on_start bool False Opt-in flag (default False). Set to True to enable the crash-resume logic. Requires ledger to be provided; ignored otherwise.

Method AutonomousOrchestrator.stop

Stop all autonomy components.

stop()

Method AutonomousOrchestrator.setup_routes

Setup HTTP routes on the aiohttp application.

setup_routes(app)

Parameter Type Default Description
app

Method AutonomousOrchestrator.add_hook

Register an external hook that triggers executions.

add_hook(hook: BaseHook) -> str

Parameter Type Default Description
hook BaseHook A BaseHook subclass instance.

Returns: str — The hook_id of the registered hook.

Method AutonomousOrchestrator.execute_agent

Execute a single agent.

execute_agent(agent_name: str, task: str, *, method_name: Optional[str] = None, user_id: Optional[str] = None, session_id: Optional[str] = None, **kwargs) -> ExecutionResult

Parameter Type Default Description
agent_name str Name of the registered agent
task str The prompt/question to send to the agent
method_name Optional[str] None Optional specific method to call (default: ask)
user_id Optional[str] None User identifier
session_id Optional[str] None Session identifier
**kwargs {} Additional arguments passed to the agent

Returns: ExecutionResult — ExecutionResult with the agent's response

Method AutonomousOrchestrator.execute_crew

Execute an AgentCrew.

    Args:
        crew_id: Name/ID of the registered crew
        task: The main task/query for the crew
        mode: Execution mode (sequential, parallel, flow, loop)
              If None, uses the crew's default mode from CrewDefinition
        agent_sequence: For sequential/loop modes, specific order of agents
        tasks: For parallel mode, list of {agent_id, query} dicts
        loop_condition: For loop mode, the stopping condition
        max_iterations: For loop mode, maximum iterations
        synthesis_prompt: Optional prompt to synthesize final results
        user_id: User identifier
        session_id: Session identifier
        **kwargs: Additional arguments passed to the crew
        
    Returns:
        ExecutionResult with the crew's CrewResult
        
    Example:
            # Sequential execution
            result = await orchestrator.execute_crew(
                "writing_team",
                task="Write a blog post about AI",
                mode="sequential"
            )
            
            # Flow execution (uses DAG from CrewDefinition)
            result = await orchestrator.execute_crew(
                "research_crew",
                task="Analyze competitor landscape",
                mode="flow"
            )
            
            # Loop execution
            result = await orchestrator.execute_crew(
                "refinement_crew",
                task="Draft initial proposal",
                mode="loop",
                loop_condition="The proposal is complete and ready for review",
                max_iterations=3
            )
            
            # Parallel execution
            result = await orchestrator.execute_crew(
                "analysis_crew",
                task="Analyze data",
                mode="parallel",
                tasks=[
                    {"agent_id": "analyst1", "query": "Analyze sales data"},
                    {"agent_id": "analyst2", "query": "Analyze marketing data"},
                ]
            )

execute_crew(crew_id: str, task: str, *, mode: Optional[Literal['sequential', 'parallel', 'flow', 'loop']] = None, agent_sequence: Optional[List[str]] = None, tasks: Optional[List[Dict[str, Any]]] = None, loop_condition: Optional[str] = None, max_iterations: int = 5, synthesis_prompt: Optional[str] = None, user_id: Optional[str] = None, session_id: Optional[str] = None, **kwargs) -> ExecutionResult

Parameter Type Default Description
crew_id str
task str
mode Optional[Literal['sequential', 'parallel', 'flow', 'loop']] None
agent_sequence Optional[List[str]] None
tasks Optional[List[Dict[str, Any]]] None
loop_condition Optional[str] None
max_iterations int 5
synthesis_prompt Optional[str] None
user_id Optional[str] None
session_id Optional[str] None
**kwargs {}

Returns: ExecutionResult

Method AutonomousOrchestrator.resume_agent

Resume an agent that was paused for human interaction.

resume_agent(session_id: str, user_input: str, state: Dict[str, Any]) -> ExecutionResult

Parameter Type Default Description
session_id str The interaction session id
user_input str The input provided by the user
state Dict[str, Any] The suspended state returned from the orchestrator

Returns: ExecutionResult — ExecutionResult from the resumed execution

Method AutonomousOrchestrator.inject_job

Inject a job for asynchronous execution.

The job is queued in Redis and processed by the job listener. Useful for fire-and-forget executions or scheduled tasks.

inject_job(target_type: Literal['agent', 'crew'], target_id: str, task: str, *, priority: int = 5, schedule_at: Optional[datetime] = None, callback_url: Optional[str] = None, **kwargs) -> str

Parameter Type Default Description
target_type Literal['agent', 'crew'] "agent" or "crew"
target_id str Name of the agent or crew
task str The task/prompt
priority int 5 1-10, lower = higher priority
schedule_at Optional[datetime] None Optional datetime to schedule execution
callback_url Optional[str] None Optional webhook URL to notify on completion
**kwargs {} Additional execution parameters

Returns: str — Unique identifier for tracking the job

Method AutonomousOrchestrator.get_job_status

Get the status of an injected job.

get_job_status(job_id: str) -> Optional[Dict[str, Any]]

Parameter Type Default Description
job_id str

Returns: Optional[Dict[str, Any]]

Method AutonomousOrchestrator.register_webhook

Register a webhook endpoint that triggers an agent or crew.

register_webhook(path: str, target_type: Literal['agent', 'crew'], target_id: str, *, secret: Optional[str] = None, transform_fn: Optional[Callable[[Dict], str]] = None, execution_mode: Optional[str] = None, **kwargs)

Parameter Type Default Description
path str URL path (e.g., "/github", "/stripe")
target_type Literal['agent', 'crew'] "agent" or "crew"
target_id str Name of the agent or crew
secret Optional[str] None HMAC secret for signature validation
transform_fn Optional[Callable[[Dict], str]] None Function to transform webhook payload to task/prompt
execution_mode Optional[str] None For crews, the execution mode to use
**kwargs {} Additional WebhookEndpoint options

Method AutonomousOrchestrator.on_event

Register an event handler that triggers an agent or crew.

on_event(pattern: str, target_type: Literal['agent', 'crew'], target_id: str, *, task_builder: Optional[Callable[[Event], str]] = None, execution_mode: Optional[str] = None, filter_fn: Optional[Callable[[Event], bool]] = None, **kwargs) -> str

Parameter Type Default Description
pattern str Event pattern to match (e.g., "order.created", "*.completed")
target_type Literal['agent', 'crew'] "agent" or "crew"
target_id str Name of the agent or crew
task_builder Optional[Callable[[Event], str]] None Function to build task from event (default: JSON of payload)
execution_mode Optional[str] None For crews, the execution mode to use
filter_fn Optional[Callable[[Event], bool]] None Optional filter to conditionally handle events
**kwargs {} Additional execution parameters

Returns: str — subscriber_id for unsubscribing

Method AutonomousOrchestrator.emit_event

Emit an event to the bus.

emit_event(event_type: str, payload: Dict[str, Any], **kwargs) -> int

Parameter Type Default Description
event_type str
payload Dict[str, Any]
**kwargs {}

Returns: int

Method AutonomousOrchestrator.get_execution_history

Get execution history with optional filtering.

get_execution_history(limit: int = 100, target_type: Optional[str] = None, success_only: bool = False) -> List[ExecutionResult]

Parameter Type Default Description
limit int 100
target_type Optional[str] None
success_only bool False

Returns: List[ExecutionResult]

Method AutonomousOrchestrator.get_stats

Get orchestrator statistics.

get_stats() -> Dict[str, Any]

Returns: Dict[str, Any]

Method AutonomousOrchestrator.resume

Re-enqueue incomplete executions found in the ledger.

Called from :meth:start when resume_on_start=True, or directly from application startup code.

Reads all traces in the ledger that have an opening event (e.g. BeforeInvokeEvent) but no matching closing event (e.g. AfterInvokeEvent, InvokeFailedEvent) and calls :meth:inject_job for each one.

BeforeToolCallEvent traces are skipped because individual tool calls cannot be replayed independently — only invoke-level traces are re-enqueued.

Idempotency note: re-enqueueing does NOT guarantee idempotent side-effects — that is the agent/tool's responsibility. This method re-queues work, not replayed effects.

resume(ledger: 'EventLedger') -> int

Parameter Type Default Description
ledger 'EventLedger' An EventLedger implementation to query for incomplete executions.

Returns: int — The number of jobs successfully re-enqueued.

Alias BaseHook

Re-exported from parrot.core.hooks.BaseHook.

Alias BotManager

Re-exported from parrot.manager.BotManager.

Alias CrewDefinition

Re-exported from parrot.models.crew_definition.CrewDefinition.

Alias EventLedger

Re-exported from parrot.autonomous.ledger.EventLedger.

Class ExecutionRequest

Represents a request to execute an agent or crew.

This is the unified interface for all trigger modes.

Parameter Type Default Description
request_id str (lambda: str(uuid.uuid4()))()
target_type ExecutionTarget ExecutionTarget.AGENT
target_id str ''
task str ''
execution_mode Optional[str] None
agent_sequence Optional[List[str]] None
tasks Optional[List[Dict[str, Any]]] None
loop_condition Optional[str] None
max_iterations int 5
synthesis_prompt Optional[str] None
user_id Optional[str] None
session_id Optional[str] None
metadata Dict[str, Any] dict()
callback_url Optional[str] None
created_at datetime datetime.now()
priority int 5

Fields:

Field Type Default Description
request_id str field(default_factory=lambda: str(uuid.uuid4()))
target_type ExecutionTarget ExecutionTarget.AGENT
target_id str ''
task str ''
execution_mode Optional[str] None
agent_sequence Optional[List[str]] None
tasks Optional[List[Dict[str, Any]]] None
loop_condition Optional[str] None
max_iterations int 5
synthesis_prompt Optional[str] None
user_id Optional[str] None
session_id Optional[str] None
metadata Dict[str, Any] field(default_factory=dict)
callback_url Optional[str] None
created_at datetime field(default_factory=datetime.now)
priority int 5

Method ExecutionRequest.to_dict

to_dict() -> Dict[str, Any]

Returns: Dict[str, Any]

Class ExecutionResult

Result of an execution request.

Parameter Type Default Description
request_id str
target_type ExecutionTarget
target_id str
success bool
result Any None
error Optional[str] None
execution_time_ms float 0.0
metadata Dict[str, Any] dict()
completed_at datetime datetime.now()

Fields:

Field Type Default Description
request_id str
target_type ExecutionTarget
target_id str
success bool
result Any None
error Optional[str] None
execution_time_ms float 0.0
metadata Dict[str, Any] field(default_factory=dict)
completed_at datetime field(default_factory=datetime.now)

Class ExecutionTarget

Type of execution target.

Alias HookEvent

Re-exported from parrot.core.hooks.HookEvent.

Alias HookManager

Re-exported from parrot.core.hooks.HookManager.

Alias RedisJobInjector

Re-exported from parrot.autonomous.redis_jobs.RedisJobInjector.

Alias SchedulerManager

Re-exported from parrot.scheduler.SchedulerManager.

Alias WebhookListener

Re-exported from parrot.autonomous.webhooks.WebhookListener.

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