DS DevShelfHub Projects · AI tools
Tutorials/ CrewAI/ Hooks & Events · API Reference →
Hooks & Events Page 20 of 29

CrewAI Hooks and Events: Instrument Agent Lifecycles

By DevShelfHub

Hooks let you intercept and modify LLM/tool exchanges. Events let you observe everything from start to finish.

Series progress20 / 29
CrewAI hooks events tutorial — CrewAI Hooks and Events: Instrument Agent Lifecycles

LLM-Call Hooks

Intercept every prompt and response with @before_llm_call_crew and @after_llm_call_crew. The context object carries prompt, response, model, agent identity — see LLMCallHookContext.

python
from crewai.hooks import before_llm_call_crew, after_llm_call_crew

@before_llm_call_crew
def redact(ctx):
    ctx.prompt = scrub_pii(ctx.prompt)

@after_llm_call_crew
def log(ctx):
    tracer.log(model=ctx.model, tokens=ctx.usage)

Tool-Call Hooks

Gate side-effecting tools, audit calls, or rewrite results. Return False to deny. See @before_tool_call_crew, @after_tool_call_crew, and the ToolCallHookContext class reference.

python
@before_tool_call_crew
def gate(ctx):
    if ctx.tool_name == "delete_record": return False

@after_tool_call_crew
def trim(ctx):
    return ctx.result[:2000]

Programmatic Registration

For plugin systems, register hooks imperatively: register_before_llm_call_hook(), register_after_llm_call_hook(), register_before_tool_call_hook(), and register_after_tool_call_hook(). Always call clear_all_global_hooks() in test fixtures.

The Event Bus

For read-only observability, subscribe a BaseEventListener to crewai_event_bus. Listeners run alongside the crew without modifying it.

python
from crewai.events import BaseEventListener, crewai_event_bus

class CostListener(BaseEventListener):
    def on_event(self, event):
        if hasattr(event, "usage"):
            metrics.incr("tokens", event.usage.total_tokens)

crewai_event_bus.subscribe(CostListener())

Event Catalog

CrewAI emits typed events across every subsystem:

  • Crew: CrewKickoffStarted/Completed/Failed, CrewTrain*, CrewTest*.
  • Agent: AgentExecutionStarted/Completed/Error, AgentEvaluation*, AgentReasoning*.
  • Task: TaskStarted/Completed/Failed, TaskEvaluation.
  • LLM: LLMCallStarted/Completed/Failed, LLMStreamChunk, LLMThinkingChunk, LLMGuardrail*.
  • Memory: MemorySave*, MemoryQuery*, MemoryRetrieval*.
  • Knowledge: KnowledgeQuery*, KnowledgeRetrieval*, KnowledgeSearchQueryFailed.
  • Tool: ToolUsageStarted/Finished, ToolExecutionError, ToolUsageError, ToolSelectionError, ToolValidateInputError.
  • Flow: FlowStarted/Finished/Created/Plot/Paused, MethodExecution*, HumanFeedback*, FlowInput*.
  • MCP: MCPConnection*, MCPToolExecution*, MCPConfigFetchFailed.
  • A2A: A2AAgentCardFetched, A2ATransportNegotiated, A2AConversation*, A2ADelegation*, A2AParallelDelegation*, A2AServerTask*, A2AContext* (Created/Completed/Expired/Idle/Pruned), A2APolling*, A2APushNotification*, A2AAuthenticationFailed, A2AConnectionError.
  • LiteAgent: LiteAgentExecutionStarted/Completed/Error.
  • Planning: StepObservationStarted/Completed/Failed, PlanRefinementEvent, PlanReplanTriggeredEvent, GoalAchievedEarlyEvent.

Notes

Hook ordering is part of your public API

Teams will rely on side effects like metrics and redaction happening in a certain sequence. Document ordering assumptions and add tests that fail if decorators reorder execution.

Heavy work in hooks slows every call

Hooks run around hot paths. Offload enrichment to async workers or sampling when you need large payload transforms.

Redact before you log to third parties

If a hook forwards events to SaaS tracing, scrub secrets first. Many incidents start with accidental prompt export, not malicious users.

Catalog coverage gaps show up in audits

When new tool types ship, update your hook matrix and regression tests. Silent misses mean compliance controls never ran.

CrewAI hooks FAQ

What are CrewAI hooks used for?

Hooks let you intercept LLM calls, tool invocations, and lifecycle transitions to enforce policies, inject telemetry, or mutate payloads in a controlled way.

How is the CrewAI event bus different from hooks?

The event bus broadcasts normalized events many subscribers can consume, while hooks are closer to interception points with return semantics depending on the API you use.

Can hooks modify CrewAI tool results?

Depending on the hook type you can normalize, redact, or reject tool payloads before agents consume them, which is useful for PII scrubbing and safety.

Do hooks impact CrewAI performance?

They add overhead proportional to your logic. Keep hook bodies fast, avoid blocking network calls on the hot path, and sample expensive telemetry in production.

Where do hooks fit with observability platforms?

Forward structured events from hooks or the bus to your tracing or logging stack so dashboards correlate agent steps with latency and token usage.

See also: DevShelfHub's CrewAI tool review for a product-level comparison, pricing notes, and links back into this tutorial series.

Quick jump: API Reference