> ## 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.

# Async Crew Kickoff

> Run PraisonAI crews with native async execution — no thread offload required

Run PraisonAI crews with native async execution from FastAPI, Jupyter, Discord bots, and other event loop contexts.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph LR
    subgraph "Native Async Flow"
        A[📋 Async Caller] --> B[🧠 praisonai.arun]
        B --> C[⚡ AgentsGenerator.agenerate_crew_and_kickoff]
        C --> D[🔧 FrameworkAdapter.arun]
        D --> E[🚀 AgentTeam.astart]
        E --> F[✅ Result]
    end
    
    classDef input fill:#8B0000,stroke:#7C90A0,color:#fff
    classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
    classDef adapter fill:#189AB4,stroke:#7C90A0,color:#fff
    classDef native fill:#10B981,stroke:#7C90A0,color:#fff
    classDef output fill:#10B981,stroke:#7C90A0,color:#fff
    
    class A input
    class B,C process
    class D adapter
    class E native
    class F output
```

## Quick Start

<Steps>
  <Step title="FastAPI Route">
    Native async execution — no worker threads, true cooperative multitasking:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from fastapi import FastAPI
    import praisonai

    app = FastAPI()

    @app.post("/run")
    async def run_crew():
        result = await praisonai.arun(agent_file="agents.yaml")
        return {"result": result}
    ```
  </Step>

  <Step title="Jupyter Notebook">
    Works directly in async cells without blocking:

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

    result = await praisonai.arun(agent_file="agents.yaml")
    print(result)
    ```
  </Step>
</Steps>

***

## How It Works

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
sequenceDiagram
    participant User
    participant praisonai
    participant AgentsGenerator
    participant FrameworkAdapter
    participant AgentTeam
    participant Result
    
    User->>praisonai: await arun(agent_file)
    praisonai->>AgentsGenerator: agenerate_crew_and_kickoff()
    AgentsGenerator->>FrameworkAdapter: arun(config, llm_config, topic)
    FrameworkAdapter->>AgentTeam: astart() 
    AgentTeam-->>FrameworkAdapter: native async result
    FrameworkAdapter-->>AgentsGenerator: result
    AgentsGenerator-->>praisonai: result
    praisonai-->>User: result
```

### What's actually async

| Adapter                       | Async path                        | Notes                           |
| ----------------------------- | --------------------------------- | ------------------------------- |
| `praisonai` (praisonaiagents) | Native — `AgentTeam.astart()`     | True cooperative async          |
| `crewai`                      | Thread offload (default fallback) | Until CrewAI exposes async      |
| `autogen` / `ag2`             | Thread offload (default fallback) | Adapter-specific implementation |

### Workflow mode

YAML files with `process: workflow` also run natively async via `YAMLWorkflowParser` + `workflow.astart()` — no extra configuration needed.

***

## Configuration Options

| Option       | Type   | Default  | Description                              |
| ------------ | ------ | -------- | ---------------------------------------- |
| `agent_file` | `str`  | Required | Path to the agent YAML file              |
| `framework`  | `str`  | `None`   | Framework to use (auto-detected if None) |
| `tools`      | `list` | `None`   | Additional tools to make available       |
| `agent_yaml` | `str`  | `None`   | Direct YAML content as string            |
| `cli_config` | `dict` | `None`   | CLI configuration overrides              |

***

## Common Patterns

### FastAPI Background Task

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
import asyncio
import praisonai
from fastapi import FastAPI, BackgroundTasks

app = FastAPI()

async def run_crew_background():
    result = await praisonai.arun(agent_file="agents.yaml")
    # Store result in database, send notification, etc.
    print(f"Background crew completed: {result}")

@app.post("/start-crew")
async def start_crew(background_tasks: BackgroundTasks):
    background_tasks.add_task(run_crew_background)
    return {"message": "Crew started"}
```

### Concurrent Crew Execution

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

async def run_multiple_crews():
    # Run all crews concurrently with true async
    results = await asyncio.gather(
        praisonai.arun(agent_file="research.yaml"),
        praisonai.arun(agent_file="analysis.yaml"),
        praisonai.arun(agent_file="summary.yaml")
    )
    
    return results
```

***

## Best Practices

<AccordionGroup>
  <Accordion title="Cancellation and timeouts propagate">
    Under native async, `asyncio.CancelledError` and `asyncio.wait_for` now actually cancel SDK work instead of being trapped behind a worker thread:

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

    async def cancelable_crew():
        try:
            # This will properly cancel if timeout is reached
            result = await asyncio.wait_for(
                praisonai.arun(agent_file="agents.yaml"),
                timeout=30.0
            )
            return result
        except asyncio.TimeoutError:
            print("Crew execution timed out and was cancelled")
            return None
    ```
  </Accordion>

  <Accordion title="Use asyncio.gather for concurrent crews">
    When running multiple crews, use `asyncio.gather` for parallel execution:

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

    # ✅ Concurrent execution with native async
    crew1_task = praisonai.arun(agent_file="crew1.yaml")
    crew2_task = praisonai.arun(agent_file="crew2.yaml")
    results = await asyncio.gather(crew1_task, crew2_task)

    # ❌ Sequential execution (slower)
    result1 = await praisonai.arun(agent_file="crew1.yaml")
    result2 = await praisonai.arun(agent_file="crew2.yaml")
    ```
  </Accordion>

  <Accordion title="Framework detection works transparently">
    All supported frameworks work with async execution — praisonai-native uses true async, others fall back to thread offload automatically:

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

    # Native async for praisonai, thread offload for crewai
    result = await praisonai.arun(agent_file="agents.yaml", framework="praisonai")
    ```
  </Accordion>

  <Accordion title="Handle errors gracefully in async contexts">
    Wrap async crew execution in try-catch blocks:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    import asyncio
    import logging
    import praisonai

    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(__name__)

    async def safe_crew_run():
        try:
            result = await praisonai.arun(agent_file="agents.yaml")
            return {"success": True, "result": result}
        except Exception as e:
            logger.error(f"Crew execution failed: {e}")
            return {"success": False, "error": str(e)}
    ```
  </Accordion>
</AccordionGroup>

***

## Related

<CardGroup cols={2}>
  <Card title="YAML Template Variables" icon="code" href="/docs/features/yaml-template-variables">
    Use {topic} placeholders safely alongside JSON literals
  </Card>

  <Card title="Framework Adapter Plugins" icon="puzzle-piece" href="/docs/features/framework-adapter-plugins">
    Custom framework adapters with async support
  </Card>
</CardGroup>
