AutoAgents
AutoAgents automatically creates and manages AI agents and tasks based on high-level instructions.
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.
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
- Install Package
First, install the PraisonAI Agents package:
bash pip install praisonaiagents duckduckgo_search - 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}" - Create a file
Create a new file
app.pywith 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) - Start AutoAgents
Run your AutoAgents:
bash python app.py
No Code
- Install Package
Install the PraisonAI package:
bash pip install praisonai - 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}" - Start AutoAgents
Run your AutoAgents:
bash praisonai --auto "Create a movie script about a robot in Mars"
How It Works
| 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 |
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.
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
Analyzes task complexity and creates 1-4 agents as needed. Simple tasks get fewer agents.
Smart Tool AssignmentAutomatically assigns relevant tools to each agent from every tool the ToolResolver can currently see — local tools.py, praisonaiagents.tools, the praisonai-tools package, wrapper ToolRegistry registrations, and core SDK plugins.
Supports 6 patterns: sequential, parallel, routing, loop, orchestrator-workers, evaluator-optimizer.
Pattern RecommendationAutomatically recommends the best workflow pattern based on task characteristics.
Workflow Patterns
Sequential (Default)
Agents work one after another, passing output to the next.
praisonai workflow auto "Research and write a blog post" --pattern sequentialParallel
Multiple agents work concurrently on independent subtasks.
praisonai workflow auto "Research from multiple sources" --pattern parallelRouting
A classifier agent routes requests to specialized agents based on input type.
praisonai workflow auto "Handle different customer requests" --pattern routingOrchestrator-Workers
A central orchestrator dynamically delegates tasks to specialized workers.
praisonai workflow auto "Comprehensive market analysis" --pattern orchestrator-workersEvaluator-Optimizer
One agent generates content, another evaluates it in a loop until quality criteria are met.
praisonai workflow auto "Write and refine a high-quality article" --pattern evaluator-optimizer# Basic usage with default settings
agents = AutoAgents(
instructions="Your high-level task description",
tools=[tool1, tool2]
)# 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
# 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
# Tasks are executed in sequence
agents = AutoAgents(
instructions="Your task",
process="sequential"
)Hierarchical Process
# Manager agent coordinates other agents
agents = AutoAgents(
instructions="Your task",
process="hierarchical",
manager_llm="gpt-4o" # Specify LLM for manager
)Best Practices
Clear Instructions
# 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
# 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
# Configure resource limits
agents = AutoAgents(
instructions="Your task",
max_rpm=60, # Rate limiting
max_execution_time=300, # Timeout
max_agents=3 # Agent limit
)Troubleshooting
If tools aren’t being assigned correctly: – Check tool compatibility – Verify tool names – Enable verbose mode for debugging
Performance IssuesIf execution is slow: – Reduce max_agents – Adjust max_rpm – Consider process type
AutoGenerator API (Python)
The framework= kwarg is honoured end-to-end — the value you pass is the value written to the YAML:
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:
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():
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())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 doneAutoGenerator Parameters
strThe task/topic for agent generation
strOutput YAML file name
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.
Optional[FrameworkAdapterRegistry]Dependency-injection hook for the framework adapter registry. Defaults to the shared registry via get_default_registry(). See Framework Adapter Plugins.
strWorkflow pattern: “sequential”, “parallel”, “routing”, “orchestrator-workers”, “evaluator-optimizer”
boolIf True, generate a single agent instead of a team
WorkflowAutoGenerator Parameters
strThe task/topic for workflow generation
strOutput YAML file name
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.
boolIf True, generate a single agent workflow
Optional[FrameworkAdapterRegistry]Dependency-injection hook for the framework adapter registry. Defaults to the shared registry via get_default_registry(). See Framework Adapter Plugins.
Methods
methodGenerate the YAML file. merge=True merges with existing file.
methodKeyword-based pattern recommendation (fast, no API call)
methodLLM-based pattern recommendation with reasoning and confidence score
async methodAsync equivalent of generate(). Uses LiteLLM async (preferred) or AsyncOpenAI (fallback). Same arguments and return value as generate().
methodExplicit cleanup of the underlying OpenAI client. Prefer with / async with context managers instead.
AutoAgents API (Runtime)
Main Parameters
strHigh-level task description for the agents
List[Any]List of tools available to the agents
intMaximum number of agents to create
strProcess type: “sequential” or “hierarchical”
Optional Parameters
boolEnable detailed logging
boolEnable agent memory
bool⚠️ Deprecated — use handoffs= instead. Allow agents to delegate tasks.
Methods
methodStart the agents synchronously
methodStart the agents asynchronously
Next Steps
Explore more examples in our examples directory
Custom ToolsLearn how to create custom tools for your agents