> ## Documentation Index
> Fetch the complete documentation index at: https://praison.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# AutoAgents

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

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
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.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph LR
    In[Goal] --> Analyze[Analyse + spawn agents]
    Analyze --> Execute[Run workflow]
    Execute --> Out[Result]

    classDef input fill:#8B0000,stroke:#7C90A0,color:#fff
    classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
    classDef output fill:#10B981,stroke:#7C90A0,color:#fff
    class In input
    class Analyze,Execute process
    class Out output
```

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

<Tabs>
  <Tab title="Code">
    <Steps>
      <Step title="Install Package">
        First, install the PraisonAI Agents package:

        ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
        pip install praisonaiagents duckduckgo_search
        ```
      </Step>

      <Step title="Set API Key">
        Set your OpenAI API key as an environment variable in your terminal:

        ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
        export OPENAI_API_KEY="${OPENAI_API_KEY:?Set OPENAI_API_KEY in your shell}"
        ```
      </Step>

      <Step title="Create a file">
        Create a new file `app.py` with the basic setup:

        ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
        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)
        ```
      </Step>

      <Step title="Start AutoAgents">
        Run your AutoAgents:

        ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
        python app.py
        ```
      </Step>
    </Steps>

    <Note>
      **Requirements**

      * Python 3.10 or higher
      * OpenAI API key. Generate OpenAI API key [here](https://platform.openai.com/api-keys). Use Other models using [this guide](/models).
    </Note>
  </Tab>

  <Tab title="No Code">
    <Steps>
      <Step title="Install Package">
        Install the PraisonAI package:

        ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
        pip install praisonai
        ```
      </Step>

      <Step title="Set API Key">
        Set your OpenAI API key as an environment variable in your terminal:

        ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
        export OPENAI_API_KEY="${OPENAI_API_KEY:?Set OPENAI_API_KEY in your shell}"
        ```
      </Step>

      <Step title="Start AutoAgents">
        Run your AutoAgents:

        ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
        praisonai --auto "Create a movie script about a robot in Mars"
        ```
      </Step>
    </Steps>
  </Tab>
</Tabs>

## How It Works

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
sequenceDiagram
    participant User
    participant AutoAgents
    participant Planner
    participant Workers

    User->>AutoAgents: start() with a high-level goal
    AutoAgents->>Planner: Analyse complexity + pick agent count
    Planner->>Workers: Create agents and assign tools
    Workers-->>AutoAgents: Execute the chosen pattern
    AutoAgents-->>User: Final result
```

| Phase      | What happens                                                 |
| ---------- | ------------------------------------------------------------ |
| 1. Analyse | AutoAgents inspects the goal and picks 1–`max_agents` agents |
| 2. Assign  | Each agent receives relevant tools automatically             |
| 3. Execute | Agents run the recommended pattern (sequential, parallel, …) |
| 4. Return  | The combined result is returned to the user                  |

## Understanding AutoAgents

<Card title="What are AutoAgents?" icon="question">
  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
</Card>

## Features

<CardGroup cols={2}>
  <Card title="Dynamic Agent Count" icon="wand-magic-sparkles">
    Analyzes task complexity and creates 1-4 agents as needed. Simple tasks get fewer agents.
  </Card>

  <Card title="Smart Tool Assignment" icon="toolbox">
    Automatically assigns relevant tools to each agent from 17+ available tools.
  </Card>

  <Card title="Workflow Patterns" icon="diagram-project">
    Supports 6 patterns: sequential, parallel, routing, loop, orchestrator-workers, evaluator-optimizer.
  </Card>

  <Card title="Pattern Recommendation" icon="lightbulb">
    Automatically recommends the best workflow pattern based on task characteristics.
  </Card>
</CardGroup>

## Workflow Patterns

<AccordionGroup>
  <Accordion title="Sequential (Default)">
    Agents work one after another, passing output to the next.

    ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    praisonai workflow auto "Research and write a blog post" --pattern sequential
    ```
  </Accordion>

  <Accordion title="Parallel">
    Multiple agents work concurrently on independent subtasks.

    ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    praisonai workflow auto "Research from multiple sources" --pattern parallel
    ```
  </Accordion>

  <Accordion title="Routing">
    A classifier agent routes requests to specialized agents based on input type.

    ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    praisonai workflow auto "Handle different customer requests" --pattern routing
    ```
  </Accordion>

  <Accordion title="Orchestrator-Workers">
    A central orchestrator dynamically delegates tasks to specialized workers.

    ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    praisonai workflow auto "Comprehensive market analysis" --pattern orchestrator-workers
    ```
  </Accordion>

  <Accordion title="Evaluator-Optimizer">
    One agent generates content, another evaluates it in a loop until quality criteria are met.

    ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    praisonai workflow auto "Write and refine a high-quality article" --pattern evaluator-optimizer
    ```
  </Accordion>
</AccordionGroup>

<CodeGroup>
  ```python Basic theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
  # Basic usage with default settings
  agents = AutoAgents(
      instructions="Your high-level task description",
      tools=[tool1, tool2]
  )
  ```

  ```python Advanced theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
  # 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
  )
  ```
</CodeGroup>

## Advanced Usage

### Configuration Options

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}

# 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

<AccordionGroup>
  <Accordion title="Sequential Process">
    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    # Tasks are executed in sequence
    agents = AutoAgents(
        instructions="Your task",
        process="sequential"
    )
    ```
  </Accordion>

  <Accordion title="Hierarchical Process">
    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    # Manager agent coordinates other agents
    agents = AutoAgents(
        instructions="Your task",
        process="hierarchical",
        manager_llm="gpt-4o"  # Specify LLM for manager
    )
    ```
  </Accordion>
</AccordionGroup>

## Best Practices

<AccordionGroup>
  <Accordion title="Clear Instructions">
    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    # 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
        """
    )
    ```
  </Accordion>

  <Accordion title="Tool Selection">
    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    # Provide relevant tools for the task

    agents = AutoAgents(
        instructions="Research task",
        tools=[
            SerperDevTool,  # For web search
            WikipediaTools,  # For background info
            CustomTool  # Your custom tool
        ]
    )
    ```
  </Accordion>

  <Accordion title="Resource Management">
    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    # Configure resource limits
    agents = AutoAgents(
        instructions="Your task",
        max_rpm=60,  # Rate limiting
        max_execution_time=300,  # Timeout
        max_agents=3  # Agent limit
    )
    ```
  </Accordion>
</AccordionGroup>

## Troubleshooting

<CardGroup cols={2}>
  <Card title="Tool Assignment Issues" icon="triangle-exclamation">
    If tools aren't being assigned correctly:

    * Check tool compatibility
    * Verify tool names
    * Enable verbose mode for debugging
  </Card>

  <Card title="Performance Issues" icon="gauge">
    If execution is slow:

    * Reduce max\_agents
    * Adjust max\_rpm
    * Consider process type
  </Card>
</CardGroup>

## AutoGenerator API (Python)

<Note>
  **Fixed in [PR #2147](https://github.com/MervinPraison/PraisonAI/pull/2147):** `WorkflowAutoGenerator.generate()` and `JobWorkflowAutoGenerator.generate()` were non-functional in all previous releases due to a `NameError` on `_models_cache`. These examples now work as shown.
</Note>

<Note>
  **Fixed in [PR #2738](https://github.com/MervinPraison/PraisonAI/pull/2738):** `WorkflowAutoGenerator(framework="crewai", ...)` now correctly writes `framework: crewai` into the generated workflow YAML. Earlier versions silently overrode the kwarg to `praisonai` — if you worked around this by hand-editing the YAML, you can drop that workaround on v4.6.134+.
</Note>

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

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
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 theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
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 theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
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())
```

<Note>
  `async with` is preferred over relying on `__del__`. The destructor was removed in PR #1736 because it leaked sockets in long-running servers. Use the context manager, or call `await gen.aclose()` explicitly.
</Note>

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
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 name="topic" type="str" required>
  The task/topic for agent generation
</ResponseField>

<ResponseField name="agent_file" type="str" default="agents.yaml">
  Output YAML file name
</ResponseField>

<ResponseField name="framework" type="str" default="praisonai">
  Framework: "praisonai", "crewai", or "autogen"
</ResponseField>

<ResponseField name="pattern" type="str" default="sequential">
  Workflow pattern: "sequential", "parallel", "routing", "orchestrator-workers", "evaluator-optimizer"
</ResponseField>

<ResponseField name="single_agent" type="bool" default="False">
  If True, generate a single agent instead of a team
</ResponseField>

### WorkflowAutoGenerator Parameters

<ResponseField name="topic" type="str" required>
  The task/topic for workflow generation
</ResponseField>

<ResponseField name="workflow_file" type="str" default="workflow.yaml">
  Output YAML file name
</ResponseField>

<ResponseField name="framework" type="str" default="praisonai">
  Framework: "praisonai", "crewai", or "autogen"
</ResponseField>

<ResponseField name="single_agent" type="bool" default="False">
  If True, generate a single agent workflow
</ResponseField>

### Methods

<ResponseField name="generate(pattern, merge)" type="method">
  Generate the YAML file. `merge=True` merges with existing file.
</ResponseField>

<ResponseField name="recommend_pattern()" type="method">
  Keyword-based pattern recommendation (fast, no API call)
</ResponseField>

<ResponseField name="recommend_pattern_llm()" type="method">
  LLM-based pattern recommendation with reasoning and confidence score
</ResponseField>

<ResponseField name="agenerate(...)" type="async method">
  Async equivalent of `generate()`. Uses LiteLLM async (preferred) or `AsyncOpenAI` (fallback). Same arguments and return value as `generate()`.
</ResponseField>

<ResponseField name="close() / aclose()" type="method">
  Explicit cleanup of the underlying OpenAI client. Prefer `with` / `async with` context managers instead.
</ResponseField>

## AutoAgents API (Runtime)

### Main Parameters

<ResponseField name="instructions" type="str" required>
  High-level task description for the agents
</ResponseField>

<ResponseField name="tools" type="List[Any]">
  List of tools available to the agents
</ResponseField>

<ResponseField name="max_agents" type="int" default="3">
  Maximum number of agents to create
</ResponseField>

<ResponseField name="process" type="str" default="sequential">
  Process type: "sequential" or "hierarchical"
</ResponseField>

### Optional Parameters

<ResponseField name="verbose" type="bool" default="False">
  Enable detailed logging
</ResponseField>

<ResponseField name="memory" type="bool" default="True">
  Enable agent memory
</ResponseField>

<ResponseField name="allow_delegation" type="bool" default="False">
  ⚠️ **Deprecated** — use `handoffs=` instead. Allow agents to delegate tasks.
</ResponseField>

### Methods

<ResponseField name="start()" type="method">
  Start the agents synchronously
</ResponseField>

<ResponseField name="astart()" type="method">
  Start the agents asynchronously
</ResponseField>

## Next Steps

<CardGroup cols={2}>
  <Card title="Examples" icon="code" href="./examples">
    Explore more examples in our examples directory
  </Card>

  <Card title="Custom Tools" icon="screwdriver-wrench" href="./tools">
    Learn how to create custom tools for your agents
  </Card>
</CardGroup>

<Note>
  For optimal results, provide clear instructions and appropriate tools for your use case.
</Note>

## Related

<CardGroup cols={2}>
  <Card icon="sitemap" href="/features/agents">
    Build multi-agent teams by hand for full control over roles and tasks.
  </Card>

  <Card icon="list-check" href="/features/planning">
    Understand how agents plan and sequence steps before executing.
  </Card>
</CardGroup>
