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

# Agents

> Understanding Agents in PraisonAI

# Understanding Agents

Agents are the core building blocks of PraisonAI. Each agent is an autonomous AI entity with specific roles, goals, and capabilities.

## Single Agent vs Multi-Agent

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph TB
    subgraph Single["🤖 Single Agent"]
        direction TB
        A1["Agent()"]
        A1 --> T1[Task]
    end
    
    subgraph Multi["👥 Multi-Agent Team"]
        direction TB
        AT["AgentTeam()"]
        AT --> AG1[🤖 Agent 1]
        AT --> AG2[🤖 Agent 2]
        AT --> AG3[🤖 Agent 3]
    end
    
    classDef single fill:#189AB4,stroke:#7C90A0,color:#fff
    classDef multi fill:#8B0000,stroke:#7C90A0,color:#fff
    classDef agent fill:#2E8B57,stroke:#7C90A0,color:#fff
    
    class A1,T1 single
    class AT multi
    class AG1,AG2,AG3 agent
```

| Use Case                             | Class       | Code                                |
| ------------------------------------ | ----------- | ----------------------------------- |
| **One agent, one task**              | `Agent`     | `Agent(instructions="...").start()` |
| **Multiple agents working together** | `AgentTeam` | `AgentTeam(agents=[...]).start()`   |

***

## Agent Architecture

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph LR
    %% Define the main flow
    Start([▶ Start]) --> Agent1
    Agent1 --> Process[⚙ Process]
    Process --> Agent2
    Agent2 --> Output([✓ Output])
    Process -.-> Agent1
    
    %% Define subgraphs for agents and their tasks
    subgraph Agent1[ ]
        Task1[📋 Task]
        AgentIcon1[🤖 AI Agent]
        Tools1[🔧 Tools]
        
        Task1 --- AgentIcon1
        AgentIcon1 --- Tools1
    end
    
    subgraph Agent2[ ]
        Task2[📋 Task]
        AgentIcon2[🤖 AI Agent]
        Tools2[🔧 Tools]
        
        Task2 --- AgentIcon2
        AgentIcon2 --- Tools2
    end

    classDef input fill:#8B0000,stroke:#7C90A0,color:#fff
    classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
    classDef tools fill:#2E8B57,stroke:#7C90A0,color:#fff
    classDef transparent fill:none,stroke:none

    class Start,Output,Task1,Task2 input
    class Process,AgentIcon1,AgentIcon2 process
    class Tools1,Tools2 tools
    class Agent1,Agent2 transparent
```

## Key Components

<CardGroup cols={2}>
  <Card title="Role & Goal" icon="target">
    Defines the agent's purpose and objectives through role definition and specific goals
  </Card>

  <Card title="Capabilities" icon="toolbox">
    Tools and functions available to the agent for task execution
  </Card>

  <Card title="Memory" icon="brain">
    Context retention and learning capabilities across interactions
  </Card>

  <Card title="Language Model" icon="microchip">
    The underlying AI model powering the agent's intelligence
  </Card>
</CardGroup>

## Component Details

### Role and Goal

<Tip>
  Clear role and goal definitions are crucial for optimal agent performance.
</Tip>

| Component     | Description                    | Example                                 |
| :------------ | :----------------------------- | :-------------------------------------- |
| **Role**      | Agent's function and expertise | Research Analyst, Code Developer        |
| **Goal**      | Specific objectives to achieve | Analyze market trends, Generate reports |
| **Backstory** | Contextual background          | Expert with 10 years of experience      |

### Capabilities

<CodeGroup>
  ```python Basic theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
  agent = Agent(
      name="Researcher",
      role="Senior Research Analyst",  # Part of System Prompt
      goal="Uncover cutting-edge developments in AI",  # Part of System Prompt
      backstory="You are an expert at a technology research group",  # Part of System Prompt
      llm="gpt-4o"
  )
  ```
</CodeGroup>

<Steps>
  <Step title="Install PraisonAI">
    Install the core package:

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

  <Step title="Configure Environment">
    ```bash Terminal theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    export OPENAI_API_KEY=your_openai_key
    ```

    Generate your OpenAI API key from [OpenAI](https://platform.openai.com/api-keys)
    Use other LLM providers like Ollama, Anthropic, Groq, Google, etc. Please refer to the [Models](/models) for more information.
  </Step>

  <Step title="Create Agent">
    Create `app.py`:

    <CodeGroup>
      ```python Single Agent theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
      from praisonaiagents import Agent

      agent = Agent(instructions="Your are a helpful AI assistant")  # System Prompt: defines WHO the agent is
      agent.start("Write a movie script about a robot in Mars")  # User Prompt: defines WHAT to do
      ```

      ```python Multi Agents theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
      from praisonaiagents import Agent, AgentTeam

      research_agent = Agent(instructions="Research about AI")  # System Prompt
      summarise_agent = Agent(instructions="Summarise research agent's findings")  # System Prompt

      agents = AgentTeam(agents=[research_agent, summarise_agent])
      agents.start()  # User Prompt (uses task descriptions)
      ```
    </CodeGroup>
  </Step>

  <Step title="Start Agents">
    Execute your script:

    ```bash Terminal theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    python app.py
    ```

    You should see:

    * Agent initialization
    * Agents progress
    * Final results
    * Generated report
  </Step>
</Steps>

## Agent Types

<CardGroup cols={3}>
  <Card title="Basic Agent" icon="user" iconType="solid">
    <AccordionGroup>
      <Accordion title="Overview">
        Perfect for straightforward tasks and direct interactions
      </Accordion>

      <Accordion title="Features">
        * Single-purpose focus
        * Direct user interaction
        * Limited tool set
        * Ideal for simple tasks
      </Accordion>
    </AccordionGroup>
  </Card>

  <Card title="Specialized Agent" icon="user-gear" iconType="solid">
    <AccordionGroup>
      <Accordion title="Overview">
        Experts in specific domains with advanced capabilities
      </Accordion>

      <Accordion title="Features">
        * Domain expertise
        * Advanced capabilities
        * Custom tools
        * Deep knowledge base
      </Accordion>
    </AccordionGroup>
  </Card>

  <Card title="Collaborative Agent" icon="users" iconType="solid">
    <AccordionGroup>
      <Accordion title="Overview">
        Designed for team-based operations and complex workflows
      </Accordion>

      <Accordion title="Features">
        * Team interaction
        * Task delegation
        * Shared context
        * Coordinated actions
      </Accordion>
    </AccordionGroup>
  </Card>
</CardGroup>

## Best Practices

<Note>
  Always implement proper error handling and resource management in your agent configurations.
</Note>

<CardGroup cols={2}>
  <Card title="Agent Design" icon="compass-drafting" iconType="solid">
    <Steps>
      <Step title="Role Definition">
        Define clear, specific roles for each agent
      </Step>

      <Step title="Goal Setting">
        Set specific, measurable goals
      </Step>

      <Step title="Tool Selection">
        Choose relevant tools for the task
      </Step>

      <Step title="Memory Setup">
        Configure appropriate memory settings
      </Step>
    </Steps>
  </Card>

  <Card title="Agent Interaction" icon="network-wired" iconType="solid">
    <Steps>
      <Step title="Communication">
        Establish clear communication protocols
      </Step>

      <Step title="Delegation">
        Define explicit delegation rules
      </Step>

      <Step title="Error Handling">
        Implement robust error handling
      </Step>

      <Step title="Resource Management">
        Set up efficient resource allocation
      </Step>
    </Steps>
  </Card>
</CardGroup>

## Async Capabilities

<CardGroup cols={1}>
  <Card title="Key Features" icon="bolt" iconType="solid">
    <Tabs>
      <Tab title="Async Support">
        ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
        async def main():
            agent = Agent(name="AsyncAgent")
            result = await agent.aprocess_task()
        ```

        * Full async/await support
        * Non-blocking operations
        * Enhanced performance
      </Tab>

      <Tab title="Parallel Execution">
        ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
        async def parallel_tasks():
            tasks = [agent1.task(), agent2.task()]
            results = await asyncio.gather(*tasks)
        ```

        * Parallel task execution
        * Efficient resource usage
        * Improved throughput
      </Tab>

      <Tab title="Integration">
        ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
        @agent.async_tool
        async def custom_tool():
            async with aiohttp.ClientSession() as session:
                # Async operations
                pass
        ```

        * Async tool integration
        * Callback support
        * Mixed sync/async operations
      </Tab>
    </Tabs>
  </Card>
</CardGroup>

## Advanced Features

<CardGroup cols={2}>
  <Card title="Memory Management" icon="brain">
    * Short-term conversation memory
    * Long-term knowledge retention
    * Context preservation
  </Card>

  <Card title="Tool Integration" icon="plug">
    * Custom tool development
    * External API integration
    * Resource access control
  </Card>
</CardGroup>

## Async Support

Agents now support asynchronous operations through the following methods:

* `achat`: Async version of the chat method
* `astart`: Async version of start method
* `aexecute_task`: Async version of execute\_task method
* `arun_task`: Async version of run\_task method
* `arun_all_tasks`: Async version of run\_all\_tasks method

### Example Usage:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
import asyncio
from praisonaiagents import Agent, Task, AgentTeam

async def main():
    # Create an async agent
    async_agent = Agent(
        name="AsyncAgent",
        role="Async Task Specialist",
        goal="Perform async operations",
        backstory="Expert in async operations",
        tools=[async_search_tool],  # Your async tool
        
    )

    # Create an async task
    async_task = Task(
        description="Perform async operation",
        expected_output="Async result",
        agent=async_agent,
        async_execution=True  # Enable async execution
    )

    # Create and start agents with async support
    agents = AgentTeam(
        agents=[async_agent],
        tasks=[async_task],
        
    )
    
    # Start async execution
    result = await agents.astart()
    print(result)

# Run the async main function
if __name__ == "__main__":
    asyncio.run(main())
```

### Key Features:

* Full async/await support
* Parallel task execution
* Async tool integration
* Async callback support
* Mixed sync/async operations

## Next Steps

<CardGroup cols={2}>
  <Card title="Create Your First Agent" icon="code" href="/code/quickstart">
    Follow our quickstart guide to create your first agent
  </Card>

  <Card title="API Reference" icon="book" href="/api/praisonaiagents/agent/agent">
    Explore the complete Agent API documentation
  </Card>
</CardGroup>
