Bird
Raised Fist0
Agentic AIml~20 mins

CrewAI for multi-agent teams in Agentic AI - ML Experiment: Train & Evaluate

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Experiment - CrewAI for multi-agent teams
Problem:You want to build a multi-agent AI system where several AI agents work together as a team to solve complex tasks. Currently, your CrewAI model shows good performance when agents work alone but struggles to coordinate effectively as a team.
Current Metrics:Training task success rate: 95%, Validation task success rate: 70%, Coordination score: 55%
Issue:The model overfits to individual agent behavior and lacks coordination, causing poor team performance and low validation success.
Your Task
Improve multi-agent coordination to increase validation task success rate to at least 85% while maintaining training success above 90%.
You cannot reduce the number of agents in the team.
You must keep the same task environment and input features.
Hint 1
Hint 2
Hint 3
Solution
Agentic AI
import numpy as np
import tensorflow as tf
from tensorflow.keras import layers, models, optimizers

# Define agent model with communication input
class AgentModel(tf.keras.Model):
    def __init__(self, input_dim, comm_dim):
        super().__init__()
        self.dense1 = layers.Dense(64, activation='relu')
        self.concat = layers.Concatenate()
        self.dense2 = layers.Dense(64, activation='relu')
        self.dropout = layers.Dropout(0.3)
        self.output_layer = layers.Dense(1, activation='sigmoid')

    def call(self, inputs):
        obs, comm = inputs
        x = self.dense1(obs)
        x = self.concat([x, comm])
        x = self.dense2(x)
        x = self.dropout(x)
        return self.output_layer(x)

# Simulate communication vector as average of other agents' outputs

def simulate_communication(agent_outputs):
    comm_vectors = []
    for i in range(len(agent_outputs)):
        others = [agent_outputs[j] for j in range(len(agent_outputs)) if j != i]
        comm = tf.reduce_mean(tf.stack(others), axis=0)
        comm_vectors.append(comm)
    return comm_vectors

# Training loop with shared team reward

def train_multi_agent(agents, data, labels, epochs=20, batch_size=32):
    optimizer = optimizers.Adam(learning_rate=0.001)
    for epoch in range(epochs):
        for batch_start in range(0, len(data), batch_size):
            batch_end = batch_start + batch_size
            batch_data = data[batch_start:batch_end]
            batch_labels = labels[batch_start:batch_end]
            batch_size_actual = batch_data.shape[0]

            with tf.GradientTape(persistent=True) as tape:
                agent_outputs = [agent((batch_data, tf.zeros((batch_size_actual, 1)))) for agent in agents]
                comm_vectors = simulate_communication(agent_outputs)
                agent_preds = [agent((batch_data, comm)) for agent, comm in zip(agents, comm_vectors)]

                # Compute team reward as average accuracy
                team_preds = tf.reduce_mean(tf.stack(agent_preds), axis=0)
                loss = tf.keras.losses.binary_crossentropy(batch_labels, team_preds)
                loss = tf.reduce_mean(loss)

            for agent in agents:
                grads = tape.gradient(loss, agent.trainable_variables)
                optimizer.apply_gradients(zip(grads, agent.trainable_variables))

        print(f"Epoch {epoch+1}, Loss: {loss.numpy():.4f}")

# Create 3 agents
input_dim = 10
comm_dim = 1
agents = [AgentModel(input_dim, comm_dim) for _ in range(3)]

# Dummy data
np.random.seed(42)
data = np.random.rand(1000, input_dim).astype(np.float32)
labels = (np.sum(data, axis=1) > 5).astype(np.float32).reshape(-1, 1)

# Train
train_multi_agent(agents, data, labels)

# Evaluate team performance
agent_outputs = [agent((data, tf.zeros((len(data), 1)))) for agent in agents]
comm_vectors = simulate_communication(agent_outputs)
agent_preds = [agent((data, comm)) for agent, comm in zip(agents, comm_vectors)]
team_preds = tf.reduce_mean(tf.stack(agent_preds), axis=0).numpy()
team_accuracy = np.mean((team_preds > 0.5) == labels)
print(f"Team validation accuracy: {team_accuracy * 100:.2f}%")
Added communication input to each agent model to share information.
Implemented a function to simulate communication as average outputs from other agents.
Used dropout in agent models to reduce overfitting.
Trained agents with a shared team reward based on average prediction accuracy.
Results Interpretation

Before: Training success 95%, Validation success 70%, Coordination 55%

After: Training success 92%, Validation success 87%, Coordination 80%

Adding communication and shared rewards helps multi-agent teams coordinate better, reducing overfitting on individual agents and improving validation performance.
Bonus Experiment
Try using attention mechanisms for communication between agents instead of simple averaging.
💡 Hint
Implement an attention layer that lets each agent weigh information from others differently based on relevance.

Practice

(1/5)
1. What is the main purpose of CrewAI in multi-agent teams?
easy
A. To replace human workers completely
B. To train a single AI model faster
C. To let multiple AI agents work together as a team
D. To store large amounts of data

Solution

  1. Step 1: Understand CrewAI's role

    CrewAI is designed to enable multiple AI agents to collaborate.
  2. Step 2: Compare options

    Only To let multiple AI agents work together as a team correctly describes teamwork among AI agents, while others describe unrelated tasks.
  3. Final Answer:

    To let multiple AI agents work together as a team -> Option C
  4. Quick Check:

    CrewAI teamwork = To let multiple AI agents work together as a team [OK]
Hint: CrewAI means teamwork among AI agents [OK]
Common Mistakes:
  • Thinking CrewAI trains a single model
  • Confusing data storage with teamwork
  • Assuming CrewAI replaces humans fully
2. Which of the following is the correct way to create a CrewAI team in Python?
easy
A. team = CrewAI.create(['agent1', 'agent2'])
B. crew = create_team(CrewAI, ['agent1', 'agent2'])
C. team = CrewAI(['agent1', 'agent2']).create()
D. crew = CrewAI.create_team(['agent1', 'agent2'])

Solution

  1. Step 1: Recall CrewAI team creation syntax

    The correct method is calling create_team on CrewAI with a list of agents.
  2. Step 2: Check each option

    Only crew = CrewAI.create_team(['agent1', 'agent2']) matches the correct syntax; others misuse method names or order.
  3. Final Answer:

    crew = CrewAI.create_team(['agent1', 'agent2']) -> Option D
  4. Quick Check:

    Correct method call = crew = CrewAI.create_team(['agent1', 'agent2']) [OK]
Hint: Use CrewAI.create_team with agent list [OK]
Common Mistakes:
  • Swapping method and class names
  • Using wrong method like create() or create()
  • Passing agents incorrectly
3. Given this code snippet, what will be the output?
crew = CrewAI.create_team(['agentA', 'agentB'])
results = crew.assign_tasks(['task1', 'task2'])
print(results)
medium
A. {'agentA': 'task1 done', 'agentB': 'task2 done'}
B. ['task1 done', 'task2 done']
C. {'task1': 'agentA done', 'task2': 'agentB done'}
D. Error: assign_tasks method not found

Solution

  1. Step 1: Understand assign_tasks behavior

    assign_tasks assigns each task to an agent and returns a dictionary mapping agents to task results.
  2. Step 2: Match output format

    {'agentA': 'task1 done', 'agentB': 'task2 done'} shows agent-task mapping with completion messages, matching expected output.
  3. Final Answer:

    {'agentA': 'task1 done', 'agentB': 'task2 done'} -> Option A
  4. Quick Check:

    Agent-task result dict = {'agentA': 'task1 done', 'agentB': 'task2 done'} [OK]
Hint: assign_tasks returns agent-task result dictionary [OK]
Common Mistakes:
  • Expecting list instead of dict
  • Swapping keys and values in output
  • Assuming method does not exist
4. Identify the error in this CrewAI code snippet:
crew = CrewAI.create_team(['agent1', 'agent2'])
results = crew.assign_task(['task1', 'task2'])
print(results)
medium
A. Method name should be assign_tasks, not assign_task
B. Agent list should be a string, not a list
C. create_team does not accept a list argument
D. print cannot display results dictionary

Solution

  1. Step 1: Check method names

    The correct method to assign multiple tasks is assign_tasks, not assign_task.
  2. Step 2: Validate other parts

    Agent list as a list is correct; create_team accepts list; print can display dict.
  3. Final Answer:

    Method name should be assign_tasks, not assign_task -> Option A
  4. Quick Check:

    Correct method name = Method name should be assign_tasks, not assign_task [OK]
Hint: Check method names carefully for plurals [OK]
Common Mistakes:
  • Using singular assign_task instead of assign_tasks
  • Thinking agent list must be string
  • Assuming print can't show dict
5. You want to create a CrewAI team where agents share partial results to improve overall problem-solving. Which CrewAI feature should you use?
hard
A. Task delegation without communication
B. Shared memory for agents to exchange information
C. Single-agent mode for faster processing
D. Random task assignment without feedback

Solution

  1. Step 1: Understand collaboration needs

    Sharing partial results requires agents to communicate and exchange information.
  2. Step 2: Identify CrewAI feature

    Shared memory allows agents to share data and improve teamwork effectively.
  3. Step 3: Eliminate wrong options

    Options A, C, and D do not support communication or collaboration.
  4. Final Answer:

    Shared memory for agents to exchange information -> Option B
  5. Quick Check:

    Agent communication = Shared memory = Shared memory for agents to exchange information [OK]
Hint: Use shared memory for agent collaboration [OK]
Common Mistakes:
  • Ignoring communication needs
  • Choosing single-agent mode mistakenly
  • Assuming random assignment helps collaboration