AutoAgents

AutoAgents automatically creates and manages AI agents and tasks based on high-level instructions.

python
from praisonaiagents import Agent

agent = Agent(name="auto-agent", instructions="Automatically plan and execute complex tasks.")
agent.start("Research, write, and publish a blog post about AI agents.")

The user gives a high-level goal; AutoAgents analyses complexity, spawns agents, assigns tools, and executes the workflow.

Diagram

Goal

Analyse + spawn agents

Run workflow

Result

AutoAgents automatically creates and manages AI agents and tasks based on high-level instructions. It now features dynamic agent count based on task complexity and supports multiple workflow patterns including orchestrator-workers and evaluator-optimizer.

Quick Start

Code

  1. Install Package

    First, install the PraisonAI Agents package:

    bash
    pip install praisonaiagents duckduckgo_search
  2. Set API Key

    Set your OpenAI API key as an environment variable in your terminal:

    bash
    export OPENAI_API_KEY="${OPENAI_API_KEY:?Set OPENAI_API_KEY in your shell}"
  3. Create a file

    Create a new file app.py with the basic setup:

    python
    from praisonaiagents import AutoAgents
    from praisonaiagents import duckduckgo
    
    # Create AutoAgents instance
    agents = AutoAgents(
        instructions="Search for information about AI Agents",
        tools=[duckduckgo],
        process="sequential",
    
        max_agents=3  # Maximum number of agents to create
    )
    
    # Start the agents
    result = agents.start()
    print(result)
  4. Start AutoAgents

    Run your AutoAgents:

    bash
    python app.py

No Code

  1. Install Package

    Install the PraisonAI package:

    bash
    pip install praisonai
  2. Set API Key

    Set your OpenAI API key as an environment variable in your terminal:

    bash
    export OPENAI_API_KEY="${OPENAI_API_KEY:?Set OPENAI_API_KEY in your shell}"
  3. Start AutoAgents

    Run your AutoAgents:

    bash
    praisonai --auto "Create a movie script about a robot in Mars"

How It Works

Diagram
WorkersPlannerAutoAgentsUserWorkersPlannerAutoAgentsUserstart() with a high-level goalAnalyse complexity + pick agent countCreate agents and assign toolsExecute the chosen patternFinal result
PhaseWhat happens
1. AnalyseAutoAgents inspects the goal and picks 1–max_agents agents
2. AssignEach agent receives relevant tools automatically
3. ExecuteAgents run the recommended pattern (sequential, parallel, …)
4. ReturnThe combined result is returned to the user

What tools does the planner see?

The --auto planner sees a live inventory of your installed tools, not a fixed list.

The planner prompt’s Available Tools: ... line is filled by get_available_tools(), which reads directly from the canonical ToolResolver. Whatever the resolver can see, the planner can plan with — install a tool package and it shows up automatically.

Diagram

Planner tool inventory

yes

no

🤖 –auto planner

ToolResolver
available?

📚 ToolResolver.list_available

🗂️ Frozen fallback list

✅ Prompt: Available Tools = live inventory

If the resolver is unavailable (import failure or an air-gapped environment), the planner falls back to a small frozen list so --auto still produces a valid plan.

Understanding AutoAgents

What are AutoAgents?

AutoAgents automatically: – Analyzes task complexity to determine optimal agent count (1-4 agents) – Creates appropriate AI agents based on your instructions – Assigns relevant tools to each agent – Recommends workflow patterns (sequential, parallel, routing, orchestrator-workers, evaluator-optimizer) – Manages execution flow between agents – Handles agent coordination and task delegation

Features

Workflow Patterns

Sequential (Default)

Agents work one after another, passing output to the next.

bash
praisonai workflow auto "Research and write a blog post" --pattern sequential
Parallel

Multiple agents work concurrently on independent subtasks.

bash
praisonai workflow auto "Research from multiple sources" --pattern parallel
Routing

A classifier agent routes requests to specialized agents based on input type.

bash
praisonai workflow auto "Handle different customer requests" --pattern routing
Orchestrator-Workers

A central orchestrator dynamically delegates tasks to specialized workers.

bash
praisonai workflow auto "Comprehensive market analysis" --pattern orchestrator-workers
Evaluator-Optimizer

One agent generates content, another evaluates it in a loop until quality criteria are met.

bash
praisonai workflow auto "Write and refine a high-quality article" --pattern evaluator-optimizer
Basic
# Basic usage with default settings
agents = AutoAgents(
    instructions="Your high-level task description",
    tools=[tool1, tool2]
)
Advanced
# Advanced usage with custom settings
agents = AutoAgents(
    instructions="Your task description",
    tools=[tool1, tool2],
    max_agents=3,
    process="hierarchical",

    memory=True,
    handoffs=[]  # Add agents for delegation
)

Advanced Usage

Configuration Options

python
# Create AutoAgents with advanced configuration
agents = AutoAgents(
    instructions="Research and summarize recent AI developments",
    tools=[SerperDevTool, WikipediaTools],
    max_agents=3,  # Maximum number of agents to create
      # Enable detailed logging
    process="hierarchical",  # Use hierarchical process
    memory=True,  # Enable memory for agents
    execution=ExecutionConfig(
        max_rpm=60,  # Maximum requests per minute
        max_execution_time=300,  # Maximum execution time
        code_execution=True,  # Enable code execution
        code_mode="safe",  # Use safe mode
    ),
    reflection=True,  # Enable agent self-reflection
      # Enable markdown formatting
)

Process Types

Sequential Process
python
# Tasks are executed in sequence
agents = AutoAgents(
    instructions="Your task",
    process="sequential"
)
Hierarchical Process
python
# Manager agent coordinates other agents
agents = AutoAgents(
    instructions="Your task",
    process="hierarchical",
    manager_llm="gpt-4o"  # Specify LLM for manager
)

Best Practices

Clear Instructions
python
# Good instruction example
agents = AutoAgents(
    instructions="""
    Research the latest developments in AI for 2024:
    1. Focus on breakthrough technologies
    2. Include real-world applications
    3. Consider future implications
    """
)
Tool Selection
python
# Provide relevant tools for the task

agents = AutoAgents(
    instructions="Research task",
    tools=[
        SerperDevTool,  # For web search
        WikipediaTools,  # For background info
        CustomTool  # Your custom tool
    ]
)
Resource Management
python
# Configure resource limits
agents = AutoAgents(
    instructions="Your task",
    max_rpm=60,  # Rate limiting
    max_execution_time=300,  # Timeout
    max_agents=3  # Agent limit
)

Troubleshooting

AutoGenerator API (Python)

The framework= kwarg is honoured end-to-end — the value you pass is the value written to the YAML:

python
from praisonai.auto import WorkflowAutoGenerator

generator = WorkflowAutoGenerator(
    topic="Research the market and produce a report",
    framework="crewai",           # honoured — YAML says `framework: crewai`
)
path = generator.generate(pattern="sequential")
print(path)

For programmatic control over agent generation:

python
from praisonai.auto import AutoGenerator, WorkflowAutoGenerator

# Generate agents.yaml
generator = AutoGenerator(
    topic="Research AI trends and write a report",
    agent_file="agents.yaml",
    framework="praisonai",  # or "crewai", "autogen"
    pattern="sequential",   # workflow pattern
    single_agent=False      # True for simple tasks
)
path = generator.generate(merge=False)

# Generate workflow.yaml
wf_generator = WorkflowAutoGenerator(
    topic="Build a customer support system",
    workflow_file="workflow.yaml",
    framework="praisonai"
)

# Get pattern recommendation (keyword-based, fast)
pattern = wf_generator.recommend_pattern()

# Get LLM-based recommendation with reasoning
recommendation = wf_generator.recommend_pattern_llm()
print(f"Pattern: {recommendation.pattern}")
print(f"Reasoning: {recommendation.reasoning}")
print(f"Confidence: {recommendation.confidence}")

# Generate with specific pattern
path = wf_generator.generate(pattern="routing", merge=False)

Async usage

For long-running servers and async pipelines, use async with and agenerate():

python
import asyncio
from praisonai.auto import AutoGenerator, WorkflowAutoGenerator, JobWorkflowAutoGenerator

async def main():
    # Agents
    async with AutoGenerator(
        topic="Research AI trends and write a report",
        framework="praisonai",
    ) as gen:
        path = await gen.agenerate(merge=False)
        print(path)

    # Workflows
    async with WorkflowAutoGenerator(
        topic="Build a customer support system",
    ) as wf:
        path = await wf.agenerate(pattern="routing")

    # Job workflows
    async with JobWorkflowAutoGenerator(
        topic="Nightly data refresh",
    ) as job:
        path = await job.agenerate(include_judge=True, include_approve=False)

asyncio.run(main())
Diagram
graph TB
    Start[🎯 Generate YAML] --> Q{Async app?}
    Q -->|No| Sync[generator.generate]
    Q -->|Yes| Async[async with ... await generator.agenerate]
    Sync --> Done[✅ YAML file]
    Async --> Done

    classDef start fill:#6366F1,stroke:#7C90A0,color:#fff
    classDef branch fill:#F59E0B,stroke:#7C90A0,color:#fff
    classDef call fill:#189AB4,stroke:#7C90A0,color:#fff
    classDef done fill:#10B981,stroke:#7C90A0,color:#fff
    class Start start
    class Q branch
    class Sync,Async call
    class Done done

AutoGenerator Parameters

ResponseField str

The task/topic for agent generation

ResponseField str

Output YAML file name

ResponseField Optional[str]

Framework to use (“praisonai”, “crewai”, or “autogen”). When omitted, resolves via the shared registry default selector — the same one praisonai.run() uses — so the generate → run round-trip agrees on defaults.

ResponseField Optional[FrameworkAdapterRegistry]

Dependency-injection hook for the framework adapter registry. Defaults to the shared registry via get_default_registry(). See Framework Adapter Plugins.

ResponseField str

Workflow pattern: “sequential”, “parallel”, “routing”, “orchestrator-workers”, “evaluator-optimizer”

ResponseField bool

If True, generate a single agent instead of a team

WorkflowAutoGenerator Parameters

ResponseField str

The task/topic for workflow generation

ResponseField str

Output YAML file name

ResponseField Optional[str]

Framework to use (“praisonai”, “crewai”, or “autogen”). When omitted, resolves via the shared registry default selector — the same one praisonai.run() uses — so the generate → run round-trip agrees on defaults. The resolved adapter must advertise SUPPORTS_WORKFLOW=True, or initialisation raises ImportError.

ResponseField bool

If True, generate a single agent workflow

ResponseField Optional[FrameworkAdapterRegistry]

Dependency-injection hook for the framework adapter registry. Defaults to the shared registry via get_default_registry(). See Framework Adapter Plugins.

Methods

ResponseField method

Generate the YAML file. merge=True merges with existing file.

ResponseField method

Keyword-based pattern recommendation (fast, no API call)

ResponseField method

LLM-based pattern recommendation with reasoning and confidence score

ResponseField async method

Async equivalent of generate(). Uses LiteLLM async (preferred) or AsyncOpenAI (fallback). Same arguments and return value as generate().

ResponseField method

Explicit cleanup of the underlying OpenAI client. Prefer with / async with context managers instead.

AutoAgents API (Runtime)

Main Parameters

ResponseField str

High-level task description for the agents

ResponseField List[Any]

List of tools available to the agents

ResponseField int

Maximum number of agents to create

ResponseField str

Process type: “sequential” or “hierarchical”

Optional Parameters

ResponseField bool

Enable detailed logging

ResponseField bool

Enable agent memory

ResponseField bool

⚠️ Deprecated — use handoffs= instead. Allow agents to delegate tasks.

Methods

ResponseField method

Start the agents synchronously

ResponseField method

Start the agents asynchronously

Next Steps

Related