Hierarchical Process

A manager agent picks which agent runs which task, one delegation turn at a time — OpenAI strict-schema native

A manager agent decides which task runs next and which agent takes it, one delegation turn at a time.

Diagram

Hierarchical Process (PraisonAIAgents)

task_id, agent_name, action

action=execute

action=stop

👤 User Goal

👔 Manager Agent
manager_llm

🔀 Delegate

🤖 Worker Agent
runs task

✅ Result

Quick Start

  1. Delegate two tasks to two agents

    The manager on manager_llm picks the next task and agent each turn.

    python
    from praisonaiagents import Agent, Task, PraisonAIAgents
    
    researcher = Agent(name="researcher", role="Research topics")
    writer = Agent(name="writer", role="Write content")
    
    tasks = [
        Task(name="research", description="Research AI trends", agent=researcher),
        Task(name="write", description="Write article about AI trends", agent=writer),
    ]
    
    team = PraisonAIAgents(
        agents=[researcher, writer],
        tasks=tasks,
        process="hierarchical",
        manager_llm="gpt-4o-mini",
    )
    team.start()
  2. See each delegation turn

    Add output="verbose" to watch the manager emit {task_id, agent_name, action} on every turn.

    python
    from praisonaiagents import Agent, Task, PraisonAIAgents
    
    researcher = Agent(name="researcher", role="Research topics")
    writer = Agent(name="writer", role="Write content")
    
    tasks = [
        Task(name="research", description="Research AI trends", agent=researcher),
        Task(name="write", description="Write article about AI trends", agent=writer),
    ]
    
    team = PraisonAIAgents(
        agents=[researcher, writer],
        tasks=tasks,
        process="hierarchical",
        manager_llm="gpt-4o-mini",
        output="verbose",
    )
    team.start()

Which hierarchical?

Two flows share the hierarchical keyword — pick the one that matches your setup.

Diagram
graph TB
    Q{Do you have a<br/>list of agents<br/>and tasks?}
    Q -->|Yes, PraisonAIAgents<br/>agents=[...], tasks=[...]| PC[Hierarchical Process<br/>THIS PAGE<br/>manager delegates by name]
    Q -->|Yes, but a step-by-step<br/>AgentFlow steps=[...]| WF[Hierarchical Workflow<br/>manager validates each step<br/>see workflow-hierarchical]

    classDef q fill:#F59E0B,stroke:#7C90A0,color:#fff
    classDef here fill:#189AB4,stroke:#7C90A0,color:#fff
    classDef other fill:#6366F1,stroke:#7C90A0,color:#fff

    class Q q
    class PC here
    class WF other

How It Works

The manager loops: it picks a task and agent, the worker runs it, and the loop repeats until the manager returns action="stop".

Diagram
🤖 Worker Agent👔 Manager (manager_llm)PraisonAIAgents👤 User🤖 Worker Agent👔 Manager (manager_llm)PraisonAIAgents👤 Userloop[until action=”stop”]team.start(“Research and write about AI”)pick next task{task_id: 0, agent_name: “researcher”, action: “execute”}run task 0 as researchertask 0 outputpick next task{task_id: 0, agent_name: “-“, action: “stop”}final aggregated result

Each turn the manager reads the goal and remaining tasks, returns a single {task_id, agent_name, action} object, and the framework runs the named agent on that task. When no work remains, the manager returns action="stop" and the team aggregates the results.


Return value

With process="hierarchical", .start(), .astart(), and .run() return the raw output of the last user-supplied task (in insertion order), never the Manager’s synthetic manager_task.

python
from praisonaiagents import Agent, Task, PraisonAIAgents

researcher = Agent(name="researcher", role="Research topics")
writer = Agent(name="writer", role="Write content")

team = PraisonAIAgents(
    agents=[researcher, writer],
    tasks=[
        Task(name="research", description="Research AI trends", agent=researcher),
        Task(name="write", description="Write article", agent=writer),
    ],
    process="hierarchical",
    manager_llm="gpt-4o-mini",
)

# Default: the final delegated task's raw output (the article), NOT the Manager's string.
article = team.start()

# All task outputs keyed by task id, including the manager_task delegation trace.
all_outputs = team.start(return_dict=True)

The framework snapshots the real task ids before injecting the Manager, so:

  • The default single-value return is the last user task’s raw output.
  • A stale manager_task from a prior run of the same team is skipped — calling .start() twice no longer returns the previous run’s Manager output on the second call.
  • Pass return_dict=True to inspect every task’s TaskOutput, keyed by task id.
  • The Manager’s own generated content lives only in the delegation trace — run with output="verbose" to see it.

Re-running the same team

Calling team.start() a second time — or starting a team where some tasks are already status == "completed" — now completes correctly instead of looping until MAX_INVALID_SELECTIONS or silently returning early.

Two fixes make this safe:

  • Stale managers excluded. Every synthetic manager_task the process injects is tracked in Process._synthetic_manager_task_ids. On a second run, the previous run’s manager (which the SDK never removes from self.tasks) is excluded from total_tasks, rejected as a delegation target by id, and left out of the delegable-ids re-prompt.
  • Counter seeded. completed_count is seeded from tasks already status == "completed" before the run starts, so pre-completed tasks are counted once via counted_task_ids and the loop can reach completion.
Diagram

Run 2

Run 1

👤 team.start

🤖 both tasks execute

📋 self.tasks: 1 completed task
+ 1 synthetic manager

👤 team.start

🔀 exclude stale manager
seed completed_count

✅ only remaining real work runs

python
from praisonaiagents import Agent, Task, PraisonAIAgents

researcher = Agent(name="researcher", role="Research topics")
writer = Agent(name="writer", role="Write content")

research = Task(name="research", description="Research AI trends", agent=researcher)
write = Task(name="write", description="Write article about AI trends", agent=writer)

team = PraisonAIAgents(
    agents=[researcher, writer],
    tasks=[research, write],
    process="hierarchical",
    manager_llm="gpt-4o-mini",
)
team.start()   # first run — both tasks execute
team.start()   # second run — completes immediately, no phantom loop

Hierarchical loop bounds

The hierarchical manager delegates tasks in a loop. Two ceilings bound it so a repeatedly-failing task cannot run the loop forever.

BoundDefaultConfigurableWhat it does
max_iter10PraisonAIAgents(max_iter=...) / AgentTeam(max_iter=...)Total manager iterations before the loop exits with Max iteration limit reached, ending hierarchical process.
MAX_TASK_RESELECTIONS3Not currently configurable per-runPer-task cap on how many times the manager may re-delegate a task that ends in status == "failed". Once exceeded, the task is added to excluded_task_ids and counted toward completed_count.
MAX_INVALID_SELECTIONS3Not configurablePer-round cap on the manager selecting non-existent task ids before the loop exits.
Diagram

no

yes

yes

yes

no

no

no

yes

🎯 Manager loop starts

🔁 iter <= max_iter?

❌ Manager status = failed

🧭 Manager picks task

⚠️ task status = failed?

♻️ reselections > 3?

🚫 exclude, count as done

▶️ execute task

✅ all tasks done?

✅ Manager status = completed

python
from praisonaiagents import Agent, Task, PraisonAIAgents

researcher = Agent(role="Researcher", instructions="Research topics")
writer = Agent(role="Writer", instructions="Write content")

task1 = Task(description="Research AI trends", agent=researcher)
task2 = Task(description="Write article", agent=writer)

team = PraisonAIAgents(
    agents=[researcher, writer],
    tasks=[task1, task2],
    process="hierarchical",
    manager_llm="gpt-4o-mini",
    max_iter=10,   # <-- bounds the manager delegation loop
)
team.start()

The Manager’s Schema

The manager returns a fixed three-field object every delegation turn.

FieldTypeRequiredDescription
task_idint✅Exact task_id from the tasks list (0-based). Never manager_task.
agent_namestr✅Name of the agent assigned to the task
actionstr✅"execute" to run the task or "stop" to end the workflow

Invalid Selections & the Synthetic manager_task

The framework injects a synthetic manager_task for the manager’s own turn — it is never a delegable task, and rejection is enforced by id so you can safely name a real Task "manager_task".

Diagram
PraisonAIAgents👔 ManagerPraisonAIAgents👔 Managerretry up to 3 times, then abort{task_id: manager_task_id, …}[ERROR] Never select manager_task. Valid ids: [0, 1, …]{task_id: 0, …}task 0 output
RuleWhat happens
Manager returns the synthetic manager_task‘s idRejected; manager is re-prompted with only the delegable ids.
Manager returns an id not in the tasks listRejected; same re-prompt path.
Manager keeps returning invalid idsAfter MAX_INVALID_SELECTIONS = 3 attempts the workflow aborts and logs an error.
A user Task is named "manager_task"Delegable as normal — the synthetic task is matched by id, not name.
Manager re-selects an already-completed task_idLogged ("Manager re-selected already-completed task {id}; ignoring re-selection."), not re-executed, and not counted twice. Loop keeps going.

Re-selecting an already-completed task

A manager re-selecting a completed task_id is now logged and ignored — completed_count advances only on a task’s first transition to completed, keyed by counted_task_ids.

Before PR #4739 the loop incremented completed_count on every status check for a selected task, so a re-selected completed task inflated the counter and let the loop exit while genuinely unexecuted tasks were still "not started". Now the counter only advances inside the execution branch, so re-selection is safe.

Run with output="verbose" to see the warning line on every re-selection — the correct signal to tighten the manager prompt or add task-completion hints.


OpenAI Strict-Mode Compatibility

Hierarchical process uses OpenAI’s strict structured-output API natively — no JSON fallback, no per-turn retry.

Under the hood, every manager delegation turn asks the LLM for a fixed 3-field object:

FieldTypeMeaning
task_idintExact task_id from the tasks list (0-based). Never manager_task.
agent_namestrName of the agent assigned to the task
actionstr"execute" to run the task, "stop" to end the workflow

The model (ManagerInstructions in praisonaiagents/process/manager_schema.py) sets extra="forbid", so its generated JSON schema includes additionalProperties: false — the exact shape OpenAI’s strict structured-output validator requires.


Manager LLM Choice

manager_llm is optional and defaults to the team’s LLM. A cheaper model is a good default for the manager, because it only picks the next task and agent — it does not do the work.

python
from praisonaiagents import Agent, Task, PraisonAIAgents

researcher = Agent(name="researcher", role="Research topics")
writer = Agent(name="writer", role="Write content")

team = PraisonAIAgents(
    agents=[researcher, writer],
    tasks=[
        Task(name="research", description="Research AI trends", agent=researcher),
        Task(name="write", description="Write article about AI trends", agent=writer),
    ],
    process="hierarchical",
    manager_llm="gpt-4o-mini",
)
team.start()

Common Patterns

Three realistic setups where a manager delegates by name.

Research → Write → Review

python
from praisonaiagents import Agent, Task, PraisonAIAgents

researcher = Agent(name="researcher", role="Research topics")
writer = Agent(name="writer", role="Write content")
reviewer = Agent(name="reviewer", role="Review and improve content")

team = PraisonAIAgents(
    agents=[researcher, writer, reviewer],
    tasks=[
        Task(name="research", description="Research AI trends", agent=researcher),
        Task(name="write", description="Write an article on the research", agent=writer),
        Task(name="review", description="Review and polish the article", agent=reviewer),
    ],
    process="hierarchical",
    manager_llm="gpt-4o-mini",
)
team.start()

Collect → Analyse → Report

python
from praisonaiagents import Agent, Task, PraisonAIAgents

collector = Agent(name="collector", role="Collect raw data")
analyst = Agent(name="analyst", role="Analyse the data")
reporter = Agent(name="reporter", role="Write the report")

team = PraisonAIAgents(
    agents=[collector, analyst, reporter],
    tasks=[
        Task(name="collect", description="Collect sales figures", agent=collector),
        Task(name="analyse", description="Analyse trends in the figures", agent=analyst),
        Task(name="report", description="Write a summary report", agent=reporter),
    ],
    process="hierarchical",
    manager_llm="gpt-4o-mini",
)
team.start()

Triage → Respond

python
from praisonaiagents import Agent, Task, PraisonAIAgents

triager = Agent(name="triager", role="Classify incoming requests")
responder = Agent(name="responder", role="Draft a response")

team = PraisonAIAgents(
    agents=[triager, responder],
    tasks=[
        Task(name="triage", description="Classify the support ticket", agent=triager),
        Task(name="respond", description="Draft a reply to the ticket", agent=responder),
    ],
    process="hierarchical",
    manager_llm="gpt-4o-mini",
)
team.start()

Best Practices

Use a cheaper manager_llm

The manager only picks the next (task_id, agent_name, action) — it does not do the actual work. gpt-4o-mini (or an equivalently cheap model on another provider) is a good default.

Give tasks descriptive names

The manager delegates by agent_name and picks tasks by task_id. A clear task description helps the manager reason about ordering.

Do not set response_format on manager_llm

The framework already asks for the strict ManagerInstructions schema and OpenAI accepts it natively. Overriding response_format re-introduces the JSON fallback.

output=&quot;verbose&quot; shows delegation turns

When debugging why the manager stops early, run with output="verbose" and read the {task_id, agent_name, action} payloads emitted on each turn.

Re-running a team is idempotent

A second team.start() on an already-completed team returns immediately. Marking individual tasks "not started" and re-running will re-execute only those. Do not manually delete the synthetic manager_task from self.tasks — the SDK now tracks and excludes it automatically.


Related