Ir al contenido

CAMEL-AI Cheat Sheet

Overview

CAMEL (Communicative Agents for Mind Exploration of Large-Scale Language Model Society) is an open-source framework for building multi-agent systems where AI agents communicate, cooperate, and solve tasks together. It pioneered the role-playing approach to multi-agent conversation, where agents are assigned roles (e.g., researcher, programmer, critic) and collaborate through structured dialogue to accomplish complex objectives.

The framework provides building blocks for agent creation, tool integration, memory systems, retrieval-augmented generation, and multi-agent orchestration. CAMEL supports various LLM backends, includes pre-built agent types (task agents, critic agents, embodied agents), and offers utilities for data generation, model evaluation, and benchmark creation.

Installation

pip install camel-ai[all]

# With specific features
pip install "camel-ai[openai]"
pip install "camel-ai[anthropic]"
pip install "camel-ai[tools]"
pip install "camel-ai[rag]"

Environment Setup

export OPENAI_API_KEY=sk-...
export ANTHROPIC_API_KEY=sk-ant-...
export GOOGLE_API_KEY=...

Core Concepts

Single Agent

from camel.agents import ChatAgent
from camel.messages import BaseMessage
from camel.models import ModelFactory
from camel.types import ModelPlatformType, ModelType

# Create model
model = ModelFactory.create(
    model_platform=ModelPlatformType.OPENAI,
    model_type=ModelType.GPT_4O,
    model_config_dict={"temperature": 0.7}
)

# Create agent
agent = ChatAgent(
    system_message=BaseMessage.make_assistant_message(
        role_name="Research Assistant",
        content="You are a helpful research assistant who provides detailed, accurate answers."
    ),
    model=model
)

# Chat
response = agent.step(
    BaseMessage.make_user_message(
        role_name="User",
        content="Explain how RAG works in 3 paragraphs."
    )
)
print(response.msg.content)

Role-Playing (Two Agents)

from camel.societies import RolePlaying
from camel.types import TaskType

# Create role-playing session
role_play = RolePlaying(
    assistant_role_name="Python Programmer",
    user_role_name="Data Scientist",
    task_prompt="Develop a machine learning pipeline for text classification using scikit-learn.",
    task_type=TaskType.CODE,
    with_task_specify=True,  # Auto-refine task description
    model=model
)

# Run conversation
print(f"Task: {role_play.task_prompt}")
print(f"Specified Task: {role_play.specified_task_prompt}")

input_msg = role_play.init_chat()
n_rounds = 0
max_rounds = 10

while n_rounds < max_rounds:
    assistant_response, user_response = role_play.step(input_msg)

    if assistant_response.terminated or user_response.terminated:
        break

    print(f"\n--- Round {n_rounds + 1} ---")
    print(f"User ({role_play.user_role_name}):\n{user_response.msg.content[:200]}")
    print(f"Assistant ({role_play.assistant_role_name}):\n{assistant_response.msg.content[:200]}")

    input_msg = assistant_response.msg
    n_rounds += 1

Agent Types

Agent TypeDescriptionUse Case
ChatAgentGeneral conversational agentQ&A, chat
TaskAgentTask-specific execution agentFocused task completion
CriticAgentEvaluates and critiques outputsQuality assurance
EmbodiedAgentAgent with tool/action capabilitiesTool-using agent
RolePlayingAgentTakes on assigned rolesCollaborative problem solving
RetrievalAgentRAG-enhanced agentDocument Q&A

Tools and Functions

from camel.agents import ChatAgent
from camel.toolkits import (
    SearchToolkit,
    MathToolkit,
    CodeExecutionToolkit,
    FileToolkit,
)

# Create agent with tools
tools = [
    *SearchToolkit().get_tools(),
    *MathToolkit().get_tools(),
    *CodeExecutionToolkit().get_tools(),
]

agent = ChatAgent(
    system_message=BaseMessage.make_assistant_message(
        role_name="Analyst",
        content="You are a data analyst with access to search, math, and code tools."
    ),
    model=model,
    tools=tools
)

response = agent.step(
    BaseMessage.make_user_message(
        role_name="User",
        content="Calculate the compound interest on $10,000 at 5% for 10 years."
    )
)
print(response.msg.content)

Custom Tools

from camel.toolkits import FunctionTool

def get_weather(city: str) -> str:
    """Get current weather for a city.

    Args:
        city: The city name.

    Returns:
        Weather description string.
    """
    import requests
    resp = requests.get(f"https://wttr.in/{city}?format=3")
    return resp.text

weather_tool = FunctionTool(get_weather)

agent = ChatAgent(
    system_message=BaseMessage.make_assistant_message(
        role_name="Weather Bot",
        content="You help users check weather."
    ),
    model=model,
    tools=[weather_tool]
)

RAG Integration

from camel.retrievers import AutoRetriever
from camel.storages import QdrantStorage
from camel.embeddings import OpenAIEmbedding

# Create retriever
retriever = AutoRetriever(
    vector_storage=QdrantStorage(
        collection_name="documents",
        path="./qdrant_data"
    ),
    embedding_model=OpenAIEmbedding()
)

# Index documents
retriever.index(
    contents=["doc1.pdf", "doc2.txt"],
    chunk_size=1000,
    chunk_overlap=200
)

# Search
results = retriever.retrieve(query="What is the architecture?", top_k=5)
for result in results:
    print(f"Score: {result.score:.3f} | {result.content[:100]}")

Multi-Agent Workforce

from camel.workforce import Workforce
from camel.agents import ChatAgent

# Create specialized agents
researcher = ChatAgent(
    system_message=BaseMessage.make_assistant_message(
        role_name="Researcher",
        content="You research topics thoroughly and provide factual information."
    ),
    model=model
)

writer = ChatAgent(
    system_message=BaseMessage.make_assistant_message(
        role_name="Writer",
        content="You write clear, engaging content based on research."
    ),
    model=model
)

reviewer = ChatAgent(
    system_message=BaseMessage.make_assistant_message(
        role_name="Reviewer",
        content="You review content for accuracy and suggest improvements."
    ),
    model=model
)

# Create workforce
workforce = Workforce(
    description="Content creation team",
    workers=[
        {"agent": researcher, "role": "researcher"},
        {"agent": writer, "role": "writer"},
        {"agent": reviewer, "role": "reviewer"}
    ]
)

# Process task
result = workforce.process_task(
    task="Write an article about the impact of RAG on enterprise AI"
)
print(result)

Configuration

Model Configuration

from camel.models import ModelFactory
from camel.types import ModelPlatformType, ModelType

# OpenAI
openai_model = ModelFactory.create(
    model_platform=ModelPlatformType.OPENAI,
    model_type=ModelType.GPT_4O,
    model_config_dict={"temperature": 0.7, "max_tokens": 4096}
)

# Anthropic
claude_model = ModelFactory.create(
    model_platform=ModelPlatformType.ANTHROPIC,
    model_type=ModelType.CLAUDE_3_5_SONNET,
    model_config_dict={"temperature": 0.5, "max_tokens": 4096}
)

# Ollama (local)
local_model = ModelFactory.create(
    model_platform=ModelPlatformType.OLLAMA,
    model_type="llama3.1",
    model_config_dict={"temperature": 0.7},
    url="http://localhost:11434/v1"
)

Memory Configuration

from camel.memories import ChatHistoryMemory, VectorDBMemory

# Chat history memory
chat_memory = ChatHistoryMemory(
    window_size=20  # Keep last 20 messages
)

# Vector memory (long-term)
vector_memory = VectorDBMemory(
    storage=QdrantStorage(collection_name="agent_memory"),
    embedding_model=OpenAIEmbedding()
)

agent = ChatAgent(
    system_message=system_msg,
    model=model,
    memory=chat_memory
)

Advanced Usage

Task Decomposition

from camel.tasks import TaskManager

task_manager = TaskManager(model=model)

# Decompose complex task
subtasks = task_manager.decompose(
    task="Build a complete RAG system for legal documents",
    max_subtasks=5
)

for i, subtask in enumerate(subtasks):
    print(f"Subtask {i+1}: {subtask.description}")
    # Assign to appropriate agent

Data Generation

from camel.datagen import RolePlayingDataGenerator

generator = RolePlayingDataGenerator(
    assistant_role="AI Teacher",
    user_role="Student",
    task_type=TaskType.AI_SOCIETY,
    model=model
)

# Generate training conversations
conversations = generator.generate(
    num_conversations=100,
    num_rounds_per_conversation=5
)

# Save as dataset
generator.save_to_jsonl("training_data.jsonl")

Troubleshooting

IssueSolution
API rate limitsAdd delays between agent turns, use cheaper models
Agents going off-topicImprove system prompts, add critic agent
Infinite conversation loopsSet max_rounds, add termination conditions
Tool execution failsCheck tool function signatures and docstrings
High token usageReduce context window, summarize history
Import errorsInstall specific extras: pip install "camel-ai[openai]"
Memory overflowUse vector memory with pruning, limit chat history
Slow multi-agent tasksUse faster models for simple subtasks
# Verify installation
python -c "import camel; print(camel.__version__)"

# Test agent
python -c "
from camel.agents import ChatAgent
from camel.messages import BaseMessage
agent = ChatAgent(system_message=BaseMessage.make_assistant_message(role_name='Test', content='You are helpful.'))
print('Agent created successfully')
"