Docs
Integrations
CrewAI

CrewAI Integration

Integrate ANTS Platform with CrewAI for automatic observability of your multi-agent workflows.

CrewAI is a framework for orchestrating autonomous AI agents that collaborate on complex tasks through defined roles and workflows.

ANTS Platform provides full observability for your CrewAI crews — traces, cost tracking, latency metrics, and error attribution — with zero changes to your crew logic.

What Gets Captured

  • Crew executions — full lifecycle from kickoff to completion
  • Agent steps — each agent's role, reasoning, and execution
  • LLM calls — model name, prompt/completion, token usage, and cost
  • Tool usage — tool name, arguments, output, and cache status
  • Task execution — task descriptions, inputs, and outputs
  • Errors — failures attributed to the exact agent, task, or LLM call

Getting Started

Step 1: Install the SDK

pip install ants-platform[crewai]

Requires Python >=3.10. This installs the Ants Platform SDK with CrewAI support.

Step 2: Set Environment Variables

Add your API credentials to your .env file:

ANTS_PLATFORM_SECRET_KEY=sk-ap-...
ANTS_PLATFORM_PUBLIC_KEY=pk-ap-...
ANTS_PLATFORM_HOST="https://app.agenticants.ai"
⚠️

Get your API keys from Project Settings > API Keys in the ANTS Platform dashboard.

Step 3: Add the EventListener

Add these lines to your crew's entry point (typically main.py):

from ants_platform import AntsPlatform
from ants_platform.crewai import EventListener
 
# Initialize the SDK (reads keys from .env)
ants_platform = AntsPlatform()
 
# Start the listener — auto-registers with CrewAI's event bus
listener = EventListener(
    agent_name="my_crew",
    agent_display_name="My Research Crew",
)
 
# Your existing crew code — no changes needed
crew.kickoff(inputs={"topic": "AI agents"})
 
# Flush to ensure all traces are sent
ants_platform.flush()

Step 4: View Traces in ANTS Platform

After running your crew, traces appear in the Traces table. Each crew run produces a single trace with a nested hierarchy:

crew (root span)
├── Researcher Agent (agent span)
│   └── LLM Call — gpt-4o-mini (generation)
├── Research Task (task span)
├── Writer Agent (agent span)
│   └── LLM Call — gpt-4o-mini (generation)
└── Writing Task (task span)
CrewAI trace hierarchy in ANTS Platform

Step 5: Monitor in Agent Command Center

Your CrewAI agents automatically appear in the Agent Command Center with full metrics — requests, success rate, cost, latency, risk, and projected spend.

CrewAI agent in Agent Command Center

Full Example

Here's a complete main.py for a CrewAI project:

from ants_platform import AntsPlatform
from ants_platform.crewai import EventListener
from my_project.crew import ResearchCrew
 
 
def run():
    # 1. Initialize Ants Platform
    ants_platform = AntsPlatform()
 
    # 2. Start the event listener
    listener = EventListener(
        agent_name="research_crew",
        agent_display_name="Research & Blog Crew v1.0",
    )
 
    # 3. Run your crew
    inputs = {"topic": "The impact of AI on the job market"}
 
    try:
        ResearchCrew().crew().kickoff(inputs=inputs)
    except Exception as e:
        raise Exception(f"Crew failed: {e}")
    finally:
        # Always flush — even on errors
        ants_platform.flush()
 
 
if __name__ == "__main__":
    run()

Adding to an Existing CrewAI Project

You only need to modify two files in your existing project:

pyproject.toml

Add ants-platform[crewai] to your dependencies:

[project]
dependencies = [
    "crewai[tools]>=0.80.0",
    "ants-platform[crewai]",
]

Project Structure

my_crew_project/
├── src/my_crew/
│   ├── config/
│   │   ├── agents.yaml       # No changes needed
│   │   └── tasks.yaml        # No changes needed
│   ├── crew.py                # No changes needed
│   ├── main.py                # Add EventListener here
│   └── tools/
│       └── custom_tool.py     # No changes needed
├── .env                       # Add ANTS_PLATFORM_* keys here
└── pyproject.toml             # Add ants-platform[crewai]

Configuration

EventListener Parameters

ParameterTypeDefaultDescription
agent_namestr"crew"Identifier for this crew in ANTS Platform (e.g., "support_crew").
agent_display_namestrNoneHuman-readable name shown in the UI (e.g., "Customer Support Crew v2").
tagsdictNoneKey-value pairs attached to all traces (e.g., {"env": "production"}).

AntsPlatform Client Options

ParameterTypeDefaultDescription
secret_keystrenv varAPI secret key
public_keystrenv varAPI public key
hoststrenv varAPI endpoint URL
timeoutint5HTTP timeout in seconds. Increase to 30 for slower local setups.

Environment Variables

VariablePurpose
ANTS_PLATFORM_SECRET_KEYAPI authentication (secret key)
ANTS_PLATFORM_PUBLIC_KEYAPI authentication (public key)
ANTS_PLATFORM_HOSTAPI endpoint (defaults to https://app.agenticants.ai)

Tags and Metadata

Add custom tags to organize and filter your crew traces:

listener = EventListener(
    agent_name="support_crew",
    agent_display_name="Customer Support Crew",
    tags={
        "environment": "production",
        "version": "2.1.0",
        "team": "customer-success",
    },
)

Tags appear in the ANTS Platform UI and can be used for filtering and grouping.

How It Works

The EventListener hooks into CrewAI's event bus on instantiation. CrewAI fires events at each stage — the listener translates them into Ants Platform observations:

CrewAI Event                    Ants Platform Observation
──────────────────              ─────────────────────────
CrewKickoffStartedEvent    →    Root span (trace created)
AgentExecutionStartedEvent →    Agent span (nested under crew)
LLMCallStartedEvent        →    Generation span (model + tokens)
LLMCallCompletedEvent      →    Update with token usage and cost
ToolUsageStartedEvent      →    Tool span (name + arguments)
ToolUsageFinishedEvent     →    Update with output
TaskStartedEvent           →    Chain span (task description)
TaskCompletedEvent         →    Update with output
*FailedEvent / *ErrorEvent →    Error attribution (level=ERROR)

Supported CrewAI Process Types

Process TypeSupportNotes
Process.sequentialFully supportedRecommended for best trace clarity
Process.hierarchicalNot yet supportedComing soon

Troubleshooting

Traces not appearing in ANTS Platform
  1. Verify ANTS_PLATFORM_SECRET_KEY and ANTS_PLATFORM_PUBLIC_KEY are set in your .env
  2. Verify ANTS_PLATFORM_HOST points to your instance (https://app.agenticants.ai)
  3. Make sure ants_platform.flush() is called after the crew finishes
  4. Increase timeout for local setups: AntsPlatform(timeout=30)
Slow startup or timeout errors

The SDK resolves the project ID via HTTP on first use. On local setups this can take a few seconds. Increase the timeout:

ants_platform = AntsPlatform(timeout=30)
ModuleNotFoundError: Please install crewai

Make sure you installed with the CrewAI extras:

pip install ants-platform[crewai]
Error handling best practices

Always wrap your crew in try/finally to ensure traces are flushed even on failure:

try:
    crew.kickoff(inputs=inputs)
except Exception as e:
    # Error is automatically captured in the trace
    logger.error(f"Crew failed: {e}")
finally:
    ants_platform.flush()

Next Steps