Camel-AI: Multi-Agent Systems That Actually Collaborate Effectively
I wanted to build a virtual company - AI agents acting as CEO, CTO, developers, and designers working together on projects. Camel-AI's role-playing framework seemed perfect, but the agents would talk in circles, forget their roles, and fail to coordinate on tasks. Here's how I built a functional multi-agent system.
Problem
When multiple agents needed to collaborate, they would get stuck agreeing with each other or asking clarifying questions indefinitely. For example, the Product Manager would propose a feature, the Developer would ask for clarification, the PM would clarify, the Developer would ask another question, and so on - never reaching a decision.
Loop detection: Same conversation pattern repeated 5 times
What I Tried
Attempt 1: Limited the number of conversation turns. This forced decisions but often cut off important discussion.
Attempt 2: Added a moderator agent. The moderator became another participant in the loop.
Attempt 3: Used stricter system prompts. This reduced collaboration and made agents less helpful.
Actual Fix
Implemented Camel-AI's task-oriented communication with explicit decision gates and conversation state tracking. Agents now have clear objectives, must reach decisions within N turns, and the system detects and breaks circular conversations.
# Multi-agent setup with communication guards
from camel.agents import ChatAgent
from camel.messages import BaseMessage
from camel.conversations import Conversation
from camel.types import RoleType
# Define agents with clear objectives
pm_agent = ChatAgent(
system_message="""You are a Product Manager.
OBJECTIVE: Define product requirements.
DECISION AUTHORITY: You make final decisions on features.
COMMUNICATION STYLE: Be decisive, not exploratory.
After 3 rounds of discussion, you MUST make a decision.
""",
role_type=RoleType.PRODUCT_MANAGER,
decision_authority=True # This agent can make final decisions
)
dev_agent = ChatAgent(
system_message="""You are a Senior Developer.
OBJECTIVE: Assess technical feasibility.
DECISION AUTHORITY: You advise but PM decides.
COMMUNICATION STYLE: Be specific about technical concerns.
If you need clarification, ask ONCE, then make assumptions.
""",
role_type=RoleType.DEVELOPER,
decision_authority=False
)
# Conversation with guards
conversation = Conversation(
agents=[pm_agent, dev_agent],
# Communication guards
max_turns=6, # Total limit
decision_required_after=3, # Must decide by turn 3
# Loop detection
detect_loops=True,
loop_threshold=2, # Alert if same point discussed 2x
break_loop_action="force_decision", # Force decision on loop
# State tracking
track_conversation_state=True,
state_save_interval=2
)
# Run with monitoring
turn_count = 0
decision_reached = False
while turn_count < 6 and not decision_reached:
# Get next agent response
response = conversation.next_turn()
# Check for decision
if "DECISION:" in response.content:
decision_reached = True
print(f"Decision reached: {response.content}")
break
# Check for loops
if conversation.is_looping():
print("Loop detected, forcing decision")
conversation.force_decision(agent=pm_agent)
break
turn_count += 1
Problem
After a few exchanges, agents would drift from their assigned roles. A Developer agent would start making product decisions, or a Designer would begin writing code. The role-playing broke down quickly.
What I Tried
Attempt 1: Added more detailed role descriptions in system prompts. Agents would still drift.
Attempt 2: Re-injected role prompts every turn. This was expensive and didn't always work.
Actual Fix
Implemented role enforcement with action validation. Each agent has defined allowed actions and outputs. Before responding, the system validates that the agent is acting within its role and authority level.
# Role enforcement with validation
from camel.agents import ChatAgent
from camel.validators import RoleValidator
# Define role permissions
role_permissions = {
"product_manager": {
"allowed_actions": ["define_requirements", "prioritize_features", "make_decisions"],
"forbidden_actions": ["write_code", "design_ui"],
"can_decide": True,
"must_consult": ["developer", "designer"]
},
"developer": {
"allowed_actions": ["assess_feasibility", "estimate_effort", "write_code"],
"forbidden_actions": ["define_requirements", "make_product_decisions"],
"can_decide": False,
"must_consult": ["product_manager"]
},
"designer": {
"allowed_actions": ["design_ui", "define_user_experience", "create_mockups"],
"forbidden_actions": ["write_code", "define_technical_specs"],
"can_decide": False,
"must_consult": ["product_manager"]
}
}
# Create validator
validator = RoleValidator(role_permissions)
# Create agents with role enforcement
pm = ChatAgent(
system_message="You are a Product Manager...",
role="product_manager",
# Enable role enforcement
enforce_role=True,
validator=validator
)
developer = ChatAgent(
system_message="You are a Senior Developer...",
role="developer",
enforce_role=True,
validator=validator
)
# Before each response, validate
def get_validated_response(agent, message):
# Generate response
response = agent.step(message)
# Validate action
validation = validator.validate_action(
role=agent.role,
action=response.action,
content=response.content
)
if not validation.is_valid:
# Re-generate with correction
correction = f"Your response violated your role. {validation.error}. Stay within your authority."
response = agent.step(message + f"\n\n{correction}")
return response
# Now agents:
# - Cannot take actions outside their role
# - Are corrected if they drift
# - Maintain consistent character
Problem
When given a complex task like "build a web app", agents would all try to do everything at once. The designer would write code, the developer would design UI, and the PM would implement features. There was no coordination or workflow.
What I Tried
Attempt 1: Manually orchestrated the workflow step by step. This defeated the purpose of autonomous agents.
Attempt 2: Used a project manager agent to coordinate. It became a bottleneck and agents would ignore its instructions.
Actual Fix
Implemented Camel-AI's workflow orchestration with stage gates and handoffs. Tasks are broken into stages, each stage has required agent roles, and completion is validated before moving to the next stage.
# Workflow orchestration with stage gates
from camel.workflows import Workflow, Stage, StageGate
from camel.agents import ChatAgent
# Define agents
pm = ChatAgent("Product Manager")
dev = ChatAgent("Developer")
designer = ChatAgent("Designer")
qa = ChatAgent("QA Engineer")
# Define workflow stages
stages = [
Stage(
name="requirements",
description="Define product requirements",
required_agents=[pm],
optional_agents=[dev, designer],
# Stage gate
gate=StageGate(
requirement="Clear requirements document",
validator=lambda msg: "REQUIREMENTS:" in msg.content,
approver=pm
)
),
Stage(
name="design",
description="Design UI/UX",
required_agents=[designer],
optional_agents=[pm],
# Must complete requirements first
depends_on=["requirements"],
gate=StageGate(
requirement="Design mockups approved",
validator=lambda msg: "DESIGN_APPROVED:" in msg.content,
approver=pm
)
),
Stage(
name="development",
description="Implement features",
required_agents=[dev],
optional_agents=[designer],
depends_on=["design"],
gate=StageGate(
requirement="Code implementation complete",
validator=lambda msg: "IMPLEMENTATION_COMPLETE:" in msg.content,
approver=dev
)
),
Stage(
name="testing",
description="Test and validate",
required_agents=[qa],
optional_agents=[dev, pm],
depends_on=["development"],
gate=StageGate(
requirement="All tests passing",
validator=lambda msg: "TESTS_PASSING:" in msg.content,
approver=qa
)
)
]
# Create workflow
workflow = Workflow(
name="web_app_development",
stages=stages,
# Coordination settings
coordination_mode="sequential", # Stages run in order
allow_parallel=False, # No parallel stages
# Handoff
handoff_method="formal", # Formal handoff between stages
handoff_template="""
STAGE COMPLETE: {from_stage}
Deliverables: {deliverables}
Next stage: {to_stage}
Assigned to: {next_agent}
""",
# Monitoring
track_progress=True,
save_checkpoints=True
)
# Execute workflow
result = workflow.run(
initial_task="Build a todo list web app",
# Callbacks
on_stage_complete=lambda stage: print(f"Completed: {stage.name}"),
on_gate_failure=lambda gate: print(f"Gate failed: {gate.requirement}")
)
# Workflow now:
# 1. Runs stages sequentially
# 2. Validates stage completion before proceeding
# 3. Formal handoffs between agents
# 4. No role confusion or duplication
What I Learned
- Communication loops need explicit breaking: Agents will talk forever without forced decision points. Set turn limits and detect loops.
- Decision authority must be clear: Not all agents should decide. Define who can make decisions and who can only advise.
- Role enforcement requires validation: System prompts aren't enough. Validate actions against role permissions.
- Workflow orchestration beats free-form: Complex tasks need structured stages with gates. Let agents be autonomous within stages, not across the whole project.
- Stage gates ensure quality: Don't proceed until criteria are met. This prevents half-finished work from moving forward.
- Formal handoffs reduce confusion: Explicitly transfer context between stages. Don't assume agents will pick up where others left off.
Production Setup
Complete setup for production multi-agent systems.
# Install Camel-AI
pip install camel-ai
# For local models (optional)
pip install llama-cpp-python
pip install transformers
Production multi-agent system:
import asyncio
from camel.agents import ChatAgent
from camel.workflows import Workflow, Stage, StageGate
from camel.validators import RoleValidator
from camel.types import RoleType, ModelType
class VirtualCompany:
"""Virtual company with multiple AI agents."""
def __init__(self):
# Role permissions
self.permissions = {
"ceo": {
"allowed": ["make_decisions", "approve_strategy", "allocate_budget"],
"forbidden": ["write_code", "design_ui"],
"decides": True
},
"cto": {
"allowed": ["technical_decisions", "approve_architecture", "assign_tasks"],
"forbidden": ["business_decisions"],
"decides": True
},
"developer": {
"allowed": ["write_code", "implement_features", "report_bugs"],
"forbidden": ["make_product_decisions", "allocate_resources"],
"decides": False
},
"designer": {
"allowed": ["design_ui", "create_mockups", "define_ux"],
"forbidden": ["write_code", "business_decisions"],
"decides": False
}
}
self.validator = RoleValidator(self.permissions)
self.agents = {}
self._create_agents()
def _create_agents(self):
"""Create agents with role enforcement."""
self.agents["ceo"] = ChatAgent(
system_message="""You are the CEO.
Focus: Business strategy and decisions.
You have final say on business matters.
Consult CTO for technical input.
""",
role="ceo",
model=ModelType.GPT_4,
enforce_role=True,
validator=self.validator
)
self.agents["cto"] = ChatAgent(
system_message="""You are the CTO.
Focus: Technical decisions and architecture.
You have final say on technical matters.
Consult CEO for business alignment.
""",
role="cto",
model=ModelType.GPT_4,
enforce_role=True,
validator=self.validator
)
self.agents["developer"] = ChatAgent(
system_message="""You are a Senior Developer.
Focus: Implementation and code quality.
You do NOT make product or business decisions.
Ask CTO for direction.
""",
role="developer",
model=ModelType.GPT_4,
enforce_role=True,
validator=self.validator
)
self.agents["designer"] = ChatAgent(
system_message="""You are a UI/UX Designer.
Focus: User experience and visual design.
You do NOT make technical or business decisions.
Ask CEO for product direction.
""",
role="designer",
model=ModelType.GPT_4,
enforce_role=True,
validator=self.validator
)
def create_workflow(self, task: str) -> Workflow:
"""Create a workflow for the task."""
return Workflow(
name="product_development",
stages=[
Stage(
name="planning",
description="Plan the product",
required_agents=[self.agents["ceo"], self.agents["cto"]],
gate=StageGate(
requirement="Product plan approved",
approver=self.agents["ceo"]
)
),
Stage(
name="design",
description="Design the UI",
required_agents=[self.agents["designer"]],
optional_agents=[self.agents["ceo"]],
depends_on=["planning"],
gate=StageGate(
requirement="Designs approved",
approver=self.agents["ceo"]
)
),
Stage(
name="development",
description="Implement features",
required_agents=[self.agents["developer"]],
optional_agents=[self.agents["cto"]],
depends_on=["design"],
gate=StageGate(
requirement="Implementation complete",
approver=self.agents["cto"]
)
)
],
coordination_mode="sequential",
max_turns_per_stage=4,
detect_loops=True
)
async def run_project(self, task: str):
"""Run a complete project."""
workflow = self.create_workflow(task)
result = await workflow.run_async(
initial_task=task,
on_stage_complete=lambda s: print(f"✓ Completed: {s.name}"),
on_gate_failure=lambda g: print(f"✗ Gate failed: {g.requirement}")
)
return result
# Usage
async def main():
company = VirtualCompany()
result = await company.run_project(
"Build a dashboard for tracking sales metrics"
)
print(f"Project success: {result.success}")
print(f"Stages completed: {len(result.completed_stages)}")
if __name__ == "__main__":
asyncio.run(main())
Monitoring & Debugging
Key metrics for multi-agent systems.
Red Flags to Watch For
- Conversation loop rate > 30%: Agents talking in circles. Check turn limits and loop detection.
- Role violation rate > 15%: Agents acting out of character. Strengthen role enforcement.
- Stage failure rate > 25%: Gates failing too often. Review requirements or agent capabilities.
- Average turns per stage > 2x expected: Inefficient communication. Check coordination settings.
- Decision rate < 50%: Agents not reaching decisions. Check decision authority settings.
Debug Commands
# Test agent interaction
camel test-interaction \
--agents ./agents_config.yaml \
--scenario "Plan a new feature" \
--max-turns 5
# Validate role permissions
camel validate-roles \
--config ./role_permissions.yaml
# Analyze workflow
camel analyze-workflow \
--workflow ./product_development.yaml \
--check-deadlocks \
--check-loops
# Monitor running workflow
camel monitor \
--workflow-id wf_123 \
--live