Revolucionando el Trabajo Colaborativo entre Agentes de IA: Introducción a CrewAI

Diseña y ejecuta arquitecturas multi-agente utilizando modelos LLM, APIs y herramientas personalizadas.
Alberto Pérez Galende
Data Scientist & Desarrollador Python

En el dinámico mundo de la inteligencia artificial, la colaboración entre agentes ya no es una visión futurista, sino una realidad tangible que está transformando la forma en que las empresas automatizan procesos, analizan datos y crean soluciones inteligentes. En este contexto, CrewAI emerge como una plataforma innovadora y de código abierto que permite diseñar, orquestar y desplegar equipos de agentes autónomos capaces de trabajar juntos hacia un objetivo común.

A diferencia de los asistentes virtuales tradicionales, CrewAI lleva la colaboración hombre-máquina un paso más allá al permitir que múltiples agentes de IA, cada uno con roles, objetivos y especializaciones únicas, colaboren de manera estructurada y eficiente. Desde la atención al cliente hasta la generación automatizada de contenido o la gestión de flujos de trabajo complejos, CrewAI abre nuevas posibilidades para construir soluciones inteligentes más sofisticadas y adaptativas.

En este blog, exploraremos qué es CrewAI, cómo funciona y profundizaremos en un caso de uso realista que demuestra el potencial de esta tecnología en un entorno empresarial. Si estás buscando una forma práctica de escalar tu arquitectura de IA o simplemente entender cómo los sistemas multiagente están dando forma al futuro del trabajo inteligente, este artículo es para ti.

Desarrollo Software

¿Cómo Funciona CrewAI?

CrewAI se basa en una arquitectura simple pero poderosa: agentes autónomos que colaboran como si fueran miembros de un equipo humano, cada uno con tareas definidas, capacidades específicas y la habilidad de comunicarse entre sí. A través de esta orquestación, es posible automatizar procesos complejos que antes requerían supervisión constante.

I. Agentes con Roles claros

Cada agente en CrewAI se define con tres atributos fundamentales:

  • Rol: Define su función dentro del equipo. Ejemplo: Investigador, Analista, Redactor, Coordinador.
  • Objetivo: Qué debe lograr ese agente. Por ejemplo, «Recopilar los datos más recientes sobre X».
  • Conocimiento: Background o herramientas que el agente puede usar (modelos de lenguaje, APIs, bases de datos, etc.).

Esto permite diseñar agentes especializados que actúan de forma autónoma y eficiente dentro de un ecosistema colaborativo.

II. Tareas en Lenguaje Natural

Las tareas se definen en lenguaje natural, facilitando su comprensión tanto para los desarrolladores como para los modelos LLM que ejecutan las instrucciones. Cada tarea se asigna a un agente específico y puede estar vinculada a los resultados de otras tareas.

Por ejemplo:

    Tarea: "Investiga los artículos académicos más relevantes sobre inteligencia artificial generativa en los últimos 12 meses".

III. Procesos Coordinados

CrewAI permite distintos tipos de flujos de trabajo:

  • Secuencial: Los agentes trabajan en cadena. Un agente completa su tarea y pasa la información al siguiente.
  • Jerárquico: Un «agente gestor» delega y coordina tareas entre otros agentes.
  • Colaborativo: Varios agentes trabajan en paralelo y combinan sus resultados.

Esto lo hace ideal para automatizar flujos de trabajo que imitan equipos reales, como el de una redacción, un equipo de producto o un área de soporte técnico.

IV. Orquestación a través de una Plantilla

Los agentes y tareas se agrupan dentro de una estructura llamada “Crew” (plantilla), que representa el equipo completo trabajando hacia un objetivo común. Esta crew se ejecuta como un todo, y puede ser fácilmente invocada desde una aplicación, un chatbot o una plataforma de datos.

Caso de uso: Meal Planner

En este caso de uso aplicado con CrewAI, desplegamos una plantilla de agentes inteligentes especializados en nutrición y planificación alimentaria. El equipo está compuesto por un Nutricionista, un Planificador de Menús y un Organizador de Compras, quienes colaboran para ofrecer una experiencia personalizada. Juntos, analizan el perfil nutricional de un cliente, diseñan menús semanales equilibrados y generan automáticamente la lista de la compra optimizada. Esta automatización demuestra cómo los agentes de IA pueden trabajar de forma coordinada para mejorar hábitos de salud y simplificar la vida diaria.

NOTA: Se necesita una API_KEY de alguna de las plataformas disponibles (OpenAI, Google, etc) para la ejecución de los LLMs.

Paso 1: Instalar dependencias

pip install crewai

Paso 2: Crear los Agentes

from crewai import Agent

# Agente Nutricionista
nutritionist_researcher = Agent(
    role="Meal Planner",
    goal="Weekly meal plan in order to {physical_goal}",
    backstory="You are an expert on nutrition. You're working on a meal prep "
              "to : {physical_goal}. "
              "The user characteristics are: {user_characteristics}. "
              "You collect information that helps you get the best meal plan for your goal. "
              "You only have to plan 14 main meals and 7 snacks per week. "
              "Take into account the following preferences: "
              "{user_preferences}. "
              "Your work is the basis for "
              "the the shopping planner to get the shopping cart ready.",
    allow_delegation=False,
	verbose=True
)

# Agente Planificador de Comidas
meal_planner = Agent(
    role="Meal Planner",
    goal="Weekly meal plan in order to {physical_goal}",
    backstory="You are an expert on nutrition. You're working on a meal prep "
              "to : {physical_goal}. "
              "You collect information that helps you get the best meal plan for your goal. "
              "You only have to plan 14 main meals and 7 snacks per week. "
              "Take into account the following preferences: "
              "{user_preferences}. "
              "Your work is the basis for "
              "the the shopping planner to get the shopping cart ready.",
    allow_delegation=False,
	verbose=True
)

# Agente Planificador de Compras
shopping_planner = Agent(
    role="Shopping Planner",
    goal="Shopping list for the meal plan",
    backstory="You are an expert on nutrition. "
              "You are working on a shopping list to get the shopping cart ready. "
              "You base your work on the meal plan provided by the Meal Planner. "
              "You have to plan the shopping list for the entire week. "
              "Select the best ingredients for the meal plan. "
              "Specify the quantity of each ingredient. "
              "You also provide the best alternatives for each ingredient. "
              "Provide at least 3 alternatives for each ingredient. "
              "Take into account the user preferences: {user_preferences}. ",
    allow_delegation=False,
    verbose=True
)

Paso 3: Crear las Tareas

from crewai import Task

# Tarea Investigación
research = Task(
    description=(
        "1. Prioritize the latest trends, key players, "
            "and noteworthy news on nutrition.\n"
        "2. Consider the target wants to {physical_goal}.\n"
        "3. Develop a detailed content outline including "
            "an key points, and a call to action.\n"
    ),
    expected_output="A comprehensive content plan document "
        "with an outline, relevant knowledge, and resources.",
    agent=nutritionist_researcher,
)

# Tarea Plan de Comidas
meal_planning = Task(
    description=(
        "1. Use the content plan to craft a reasonable "
            "meal plan to {physical_goal}.\n"
        "2. Incorporate as much types of food as possible.\n"
        "3. Take into account the user preferences: "
            "{user_preferences}.\n"
        "4. Ensure the meal plan is structured with "
            "14 main meals and 14 snacks or small meals.\n"
        "5. Present the meal plan in a clear and organized "
            "format as a table.\n"
        "6. Proofread for grammatical errors and "
            "alignment with the brand's voice.\n"
    ),
    expected_output="A well-written markdown document "
        "with a meal plan for the week, "
        "including a table with the meals and snacks.",
    agent=meal_planner,
)

# Tarea Plan de Compras
shopping_planning = Task(
    description=("Based on the meal plan, create a shopping list "
                "for the week. "
                    "Include the following:\n"
        "1. A list of all the ingredients needed for the meals.\n"
        "2. The quantity of each ingredient.\n"
        "3. The best alternatives for each ingredient.\n"
        "4. At least 3 alternatives for each ingredient.\n"
        "5. Take into account the user preferences: "
            "{user_preferences}.\n"
        "6. Ensure the shopping list is structured and "
            "easy to follow.\n"
        "7. Proofread for grammatical errors and "
            "alignment with the brand's voice.\n"
    ),
    expected_output="A well-written list of elements with two sections, one for main meals and other for snacks, in markdown format, "
                    "ready for publication.",
    agent=shopping_planner
)

Paso 4: Ejecutar la Plantilla

from crewai import Crew

crew = Crew(
    agents=[nutritionist_researcher, meal_planner, shopping_planner],
    tasks=[research, meal_planning, shopping_planning],
    full_output=True,
    verbose=2
)

result = crew.kickoff(inputs={"physical_goal": "lose weight",
                              "user_characteristics": "{age: 30, height: 175cm, weight: 70kg}",
                              "user_preferences": "I do not like fish. I do not like spicy food. I cannot stand seafood."
}
)

Paso 5: Mostrar los Resultados

1. Muestra el Plan de Comidas
from IPython.display import Markdown

Markdown(result["tasks_outputs"][1].exported_output) # Muestra la salida del preparador de comidas

Meal Plan for Weight Loss

Introduction

Nutrition plays a crucial role in weight loss. It is important to focus on balanced meals that include lean protein, complex carbohydrates, and healthy fats. Taking into account the user’s preferences and dietary restrictions, such as not liking fish, spicy food, or seafood, we can create a customized meal plan to help achieve weight loss goals.

Meal Plan
DayMain MealsSnacks/Small Meals
MondayBreakfast: Greek yogurt with berries
Lunch: Turkey and avocado wrap
Dinner: Grilled chicken with quinoa and roasted vegetables
Snack: Apple slices with almond butter
Snack: Carrot sticks with hummus
TuesdayBreakfast: Oatmeal with banana and nuts
Lunch: Quinoa salad with chickpeas and veggies
Dinner: Lean beef stir-fry with brown rice
Snack: Greek yogurt with honey
Snack: Mixed nuts
WednesdayBreakfast: Smoothie with spinach, banana, and protein powder
Lunch: Lentil soup with whole grain bread
Dinner: Baked chicken with sweet potato and green beans
Snack: Cottage cheese with pineapple
Snack: Rice cakes with peanut butter
ThursdayBreakfast: Whole grain toast with avocado and eggs
Lunch: Grilled vegetable and tofu salad
Dinner: Turkey meatballs with zucchini noodles
Snack: Berries with cottage cheese
Snack: Trail mix
FridayBreakfast: Chia seed pudding with mixed berries
Lunch: Brown rice bowl with beans and salsa
Dinner: Salmon (substitute with chicken if preferred) with quinoa and asparagus
Snack: Celery sticks with almond butter
Snack: Edamame
SaturdayBreakfast: Scrambled eggs with spinach and tomatoes
Lunch: Vegetable stir-fry with tofu and brown rice
Dinner: Turkey chili with cornbread muffin
Snack: Banana with peanut butter
Snack: Greek yogurt with granola
SundayBreakfast: Whole grain pancakes with fruit toppings
Lunch: Chickpea salad with cucumbers and tomatoes
Dinner: Grilled steak with roasted potatoes and green salad
Snack: Rice cakes with avocado
Snack: Popcorn
Conclusion

This meal plan provides a variety of nutrient-dense foods that can aid in weight loss. By following this plan consistently and incorporating portion control, the user can achieve their weight loss goals. It is important to stay motivated and make healthy choices throughout the week. If needed, seeking guidance from a healthcare professional or nutritionist is recommended for personalized advice and support.

2. Muestra el Plan de Compras
Markdown(result["tasks_outputs"][2].exported_output) # Muestra la salida del preparador de compras

Shopping List for the Week

Main Meals Ingredients:
Monday:
  • Greek yogurt: 32 oz
    • Alternatives: Skyr, plant-based yogurt, coconut yogurt
  • Berries: 2 cups
    • Alternatives: Sliced peaches, diced apples, grapes
  • Turkey breast: 1 lb
    • Alternatives: Chicken breast, tofu, seitan
  • Avocado: 2
    • Alternatives: Hummus, guacamole, nuts
  • Whole wheat wraps: 4
    • Alternatives: Lettuce wraps, brown rice tortillas, collard green wraps
  • Quinoa: 2 cups
    • Alternatives: Brown rice, farro, barley
  • Assorted vegetables for grilling: 1 lb
    • Alternatives: Zucchini, bell peppers, mushrooms
Tuesday:
  • Oatmeal: 2 cups
    • Alternatives: Quinoa flakes, buckwheat groats, millet
  • Banana: 4
    • Alternatives: Kiwi, mango, pineapple
  • Nuts: 1 cup
    • Alternatives: Seeds (chia, flax), dried fruit, granola
  • Chickpeas: 1 can
    • Alternatives: Black beans, lentils, edamame
  • Lean beef: 1 lb
    • Alternatives: Ground turkey, tempeh, seitan
  • Brown rice: 2 cups
    • Alternatives: Bulgur, wild rice, barley
Wednesday:
  • Spinach: 2 cups
    • Alternatives: Kale, Swiss chard, arugula
  • Protein powder: 1 scoop
    • Alternatives: Collagen peptides, hemp protein, pea protein
  • Lentils: 1 cup
    • Alternatives: Black beans, kidney beans, split peas
  • Whole grain bread: 1 loaf
    • Alternatives: Gluten-free bread, sprouted grain bread, pita bread
  • Chicken breasts: 1 lb
    • Alternatives: Tofu, tempeh, seitan
  • Sweet potatoes: 2
    • Alternatives: Butternut squash, pumpkin, carrots
Thursday:
  • Whole grain bread: 1 loaf
    • Alternatives: Gluten-free bread, sprouted grain bread, pita bread
  • Eggs: 1 dozen
    • Alternatives: Tofu scramble, egg whites, vegan egg substitute
  • Grilled vegetables (zucchini, bell peppers, mushrooms): 1 lb
    • Alternatives: Roasted vegetables, steamed vegetables, stir-fried vegetables
  • Tofu: 1 block
    • Alternatives: Tempeh, seitan, edamame
  • Ground turkey: 1 lb
    • Alternatives: Chicken breast, lean beef, lentils
  • Zucchini: 2
    • Alternatives: Cucumber, yellow squash, eggplant
Friday:
  • Chia seeds: 1/2 cup
    • Alternatives: Flaxseeds, hemp seeds, sunflower seeds
  • Mixed berries: 2 cups
    • Alternatives: Diced apples, grapes, sliced peaches
  • Almond butter: 16 oz
    • Alternatives: Peanut butter, cashew butter, sunflower seed butter
  • Celery: 1 bunch
    • Alternatives: Carrot sticks, cucumber slices, bell pepper strips
  • Edamame: 1 cup
    • Alternatives: Chickpeas, black beans, lentils
  • Quinoa: 2 cups
    • Alternatives: Brown rice, farro, barley
Saturday:
  • Eggs: 1 dozen
    • Alternatives: Tofu scramble, egg whites, vegan egg substitute
  • Spinach: 2 cups
    • Alternatives: Kale, Swiss chard, arugula
  • Tomatoes: 4
    • Alternatives: Bell peppers, cucumber, zucchini
  • Tofu: 1 block
    • Alternatives: Tempeh, seitan, edamame
  • Brown rice: 2 cups
    • Alternatives: Bulgur, wild rice, barley
Sunday:
  • Whole grain pancake mix: 1 box
    • Alternatives: Gluten-free pancake mix, oat flour, buckwheat flour
  • Fruit toppings (berries, sliced bananas): 2 cups
    • Alternatives: Diced apples, mango chunks, kiwi slices
  • Chickpeas: 1 can
    • Alternatives: Black beans, lentils, edamame
  • Cucumbers: 2
    • Alternatives: Bell peppers, cherry tomatoes, radishes
  • Sirloin steak: 1 lb
    • Alternatives: Chicken breast, tofu, tempeh
  • Potatoes: 4
    • Alternatives: Sweet potatoes, butternut squash, parsnips
Snacks/Small Meals Ingredients:
  • Almond butter: 16 oz
    • Alternatives: Peanut butter, cashew butter, sunflower seed butter
  • Apple slices: 4
    • Alternatives: Pear slices, orange segments, grapes
  • Carrot sticks: 4
    • Alternatives: Cucumber slices, bell pepper strips, cherry tomatoes
  • Hummus: 1 cup
    • Alternatives: Guacamole, tzatziki, baba ganoush
  • Cottage cheese: 16 oz
    • Alternatives: Greek yogurt, skyr, kefir
  • Pineapple chunks: 2 cups
    • Alternatives: Mango chunks, papaya, kiwi slices
  • Rice cakes: 1 pack
    • Alternatives: Corn thins, whole grain crackers, rice crackers
  • Peanut butter: 16 oz
    • Alternatives: Almond butter, cashew butter, sunflower seed butter
  • Mixed nuts: 1 cup
    • Alternatives: Trail mix, roasted chickpeas, rice crackers
  • Greek yogurt: 32 oz
    • Alternatives: Skyr, plant-based yogurt, coconut yogurt
  • Honey: 1 bottle
    • Alternatives: Maple syrup, agave nectar, date syrup
  • Celery sticks: 4
    • Alternatives: Cucumber slices, bell pepper strips, cherry tomatoes
  • Edamame: 1 cup
    • Alternatives: Chickpeas, black beans, lentils
  • Berries: 2 cups
    • Alternatives: Sliced peaches, diced apples, grapes
  • Avocado: 2
    • Alternatives: Hummus, guacamole, nuts
  • Rice cakes: 1 pack
    • Alternatives: Corn thins, whole grain crackers, rice crackers
  • Almond butter: 16 oz
    • Alternatives: Peanut butter, cashew butter, sunflower seed butter
  • Granola: 1 bag
    • Alternatives: Muesli, oat clusters, granola bars

This shopping list includes all the ingredients needed for the meal plan for the week, taking into account the user’s preferences and providing alternatives for each ingredient. It is structured by main meals and snacks for easy reference and ensures a balanced and nutritious diet to support weight loss goals.

Conclusión

CrewAI representa un salto significativo en la evolución de los sistemas de inteligencia artificial, al permitir la creación de equipos autónomos de agentes que colaboran de forma estructurada y eficiente. Su enfoque modular, basado en roles y tareas definidas en lenguaje natural, facilita la automatización de procesos complejos y adaptables a distintos sectores. Ya no se trata solo de tener un modelo potente, sino de orquestar múltiples inteligencias trabajando juntas hacia un objetivo común. Para empresas y desarrolladores, CrewAI abre la puerta a soluciones más escalables, inteligentes y alineadas con los desafíos del mundo real. El futuro de la IA no es individual, es colaborativo.