# Using the CrewAI CLI within an existing FastAPI application

**URL:** <https://community.crewai.com/t/using-the-crewai-cli-within-an-existing-fastapi-application/2514>\
**Category:** General\
**Created:** [January 6, 2025, 2:25pm UTC](https://community.crewai.com/t/using-the-crewai-cli-within-an-existing-fastapi-application/2514 "2025-01-06T14:25:50Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![coderberry](https://sea1.discourse-cdn.com/flex025/user_avatar/community.crewai.com/coderberry/32/632_2.png) [@coderberry](https://community.crewai.com/u/coderberry)\
**Post date:** [January 6, 2025, 2:25pm UTC](https://community.crewai.com/t/using-the-crewai-cli-within-an-existing-fastapi-application/2514/1 "2025-01-06T14:25:50Z")

</div>

Hey all,

I’m building a slack bot application using FastAPI, slack-bolt, etc. I want to enable crews within the application but I find that utilizing the CLI is very nice and offers a lot of benefits.

Has anyone found a good pattern for building crews within a FastAPI app other than manually creating them?

Thanks!

---

<div class="post-metadata">

**Author:** ![coderberry](https://sea1.discourse-cdn.com/flex025/user_avatar/community.crewai.com/coderberry/32/632_2.png) [@coderberry](https://community.crewai.com/u/coderberry)\
**Post date:** [January 6, 2025, 2:30pm UTC](https://community.crewai.com/t/using-the-crewai-cli-within-an-existing-fastapi-application/2514/2 "2025-01-06T14:30:28Z")

</div>

It looks like I should have just asked the CrewAI GPT

Building crews within a FastAPI application while leveraging the CrewAI framework is absolutely possible and can be a highly effective way to integrate AI orchestration into your app. However, using the CrewAI CLI inside an existing application has limitations, especially since the CLI is designed for standalone projects.

Here’s a structured approach to achieve your goals:

* * *

### **Plan:**

1. **Use the CrewAI Framework Directly** :

2. **Testing and Training with CLI** :

3. **Integration into FastAPI** :

4. **Unified Dependency Management** :

* * *

### **Implementation Details**

#### **1. Initialize CrewAI in FastAPI**

Set up CrewAI within your FastAPI project. Here’s an example structure:

```auto
app/
├── main.py # FastAPI application entry point
├── crews/
│ ├── agents.yaml
│ ├── tasks.yaml
│ ├── crew_manager.py # Module to handle CrewAI logic
├── requirements.txt

```

#### **2. Code Example for `crew_manager.py`**

```python
import os
from crewai import Agent, Task, Crew, Process

# Optional: Use environment variables for API keys
os.environ["OPENAI_API_KEY"] = "your_openai_api_key"

def create_crew():
    # Define agents
    researcher = Agent(
        role='Researcher',
        goal='Conduct thorough research on {topic}',
        verbose=True,
        memory=True,
        backstory='A diligent researcher passionate about uncovering insights.',
    )

    writer = Agent(
        role='Writer',
        goal='Write a compelling article about {topic}',
        verbose=True,
        memory=True,
        backstory='A creative writer who simplifies complex topics.',
    )

    # Define tasks
    research_task = Task(
        description=(
            "Research the topic and gather key points."
            "Your report should include the pros and cons."
        ),
        expected_output='A detailed summary of the topic.',
        agent=researcher,
    )

    write_task = Task(
        description=(
            "Write an article based on the research."
            "Make it engaging and informative."
        ),
        expected_output='A 500-word article in markdown format.',
        agent=writer,
    )

    # Define crew
    crew = Crew(
        agents=[researcher, writer],
        tasks=[research_task, write_task],
        process=Process.sequential,
    )

    return crew

def kickoff_crew(inputs):
    crew = create_crew()
    return crew.kickoff(inputs=inputs)

```

#### **3. Expose Crews in FastAPI**

```python
from fastapi import FastAPI
from crews.crew_manager import kickoff_crew

app = FastAPI()

@app.post("/kickoff/")
async def kickoff_crew_endpoint(inputs: dict):
    result = kickoff_crew(inputs)
    return {"result": result}

```

* * *

### **Testing and Training**

1. **Testing Within the Application** :

2. **Adapting CLI-Like Features** :

3. **Avoid Duplicate Environments** :

* * *

### **Pros of This Approach** :

- **Unified Dependency Management** : All dependencies are managed within the FastAPI app.
- **Tight Integration** : Crews are integrated into your app logic, ensuring seamless execution.
- **Testing Flexibility** : Use both FastAPI endpoints and CLI-like scripts for testing and training.

### **Cons** :

- CLI testing may require adaptation (e.g., creating scripts or endpoints).
- Requires structured code to manage CrewAI’s configurations dynamically.

* * *

This method avoids the need for separate `requirements.txt` or repositories and aligns perfectly with the integration of crews into a FastAPI application. Let me know if you need assistance setting up any specific part!

---

<div class="post-metadata">

**Author:** ![Krish\_Sagili](https://sea1.discourse-cdn.com/flex025/user_avatar/community.crewai.com/krish_sagili/32/1322_2.png) [@Krish\_Sagili](https://community.crewai.com/u/Krish_Sagili)\
**Post date:** [January 6, 2025, 5:32pm UTC](https://community.crewai.com/t/using-the-crewai-cli-within-an-existing-fastapi-application/2514/3 "2025-01-06T17:32:30Z")

</div>

Thank you for doing this. This is what I was looking for.

---

<div class="post-metadata">

**Author:** ![beast](https://avatars.discourse-cdn.com/v4/letter/b/97f17d/32.png) [@beast](https://community.crewai.com/u/beast)\
**Post date:** [February 27, 2025, 4:58pm UTC](https://community.crewai.com/t/using-the-crewai-cli-within-an-existing-fastapi-application/2514/4 "2025-02-27T16:58:06Z")

</div>

@coderberry How do you suggest enabling a seamless and dynamic interaction between the front-end and CrewAI? I want the front-end to receive responses in real-time rather than just executing a single command. Ideally, I’d like to establish a continuous, interactive exchange between the two systems. Would love to hear your thoughts on the best approach!

---

<div class="post-metadata">

**Author:** ![stg](https://avatars.discourse-cdn.com/v4/letter/s/a4c791/32.png) [@stg](https://community.crewai.com/u/stg)\
**Post date:** [January 5, 2026, 11:36am UTC](https://community.crewai.com/t/using-the-crewai-cli-within-an-existing-fastapi-application/2514/5 "2026-01-05T11:36:01Z")

</div>

I am actually worried that the crew execution is often taking multiple seconds and this means that the request triggering the crew might time out before the result being returned. What I think makes more sense is to generate an ID for the request and the initial POST request to return the ID of the request only and then to add a GET endpoint to check the status of the request, and eventually this will return the completed result, once the crew execution is completed. This can be achieved with BackgroundTasks in FastAPI, and to start the crew execution as a background task and return some arbitrary UUID.

Actually, I found another user who implemented exactly this: [Deploying CrewAI as an API service - #20 by italiano](https://community.crewai.com/t/deploying-crewai-as-an-api-service/726/20)
