Module: ActiveAgent::Callbacks

Extended by:
ActiveSupport::Concern
Included in:
Base
Defined in:
lib/active_agent/concerns/callbacks.rb

Overview

Provides callback hooks for generation, prompting, and embedding lifecycles.

Enables agents to execute custom logic before, after, or around AI operations. Callbacks support conditional execution via ‘:if` and `:unless` options, and after callbacks are skipped when the chain is terminated with `throw :abort`.

Callback Types

Each lifecycle supports three timing hooks:

  • before_* - executes before the operation

  • after_* - executes after the operation (skipped if aborted)

  • around_* - wraps the operation (must call yield)

Lifecycle Hierarchies

  • generation - wraps both prompting and embedding operations

  • prompting - specific to prompt execution

  • embedding - specific to embedding operations

Use *_generation callbacks for cross-cutting concerns like rate limiting, authentication, and logging that apply to all AI operations.

Callback Control

  • prepend_* - inserts callback at the beginning of the chain

  • append_* - adds callback at the end (same as base methods)

  • skip_* - removes a previously defined callback

Examples:

Rate limiting with generation callbacks

class MyAgent < ActiveAgent::Base
  before_generation :check_rate_limit
  after_generation :record_usage

  def check_rate_limit
    raise RateLimitExceeded if RateLimiter.exceeded?(user_id)
  end

  def record_usage
    RateLimiter.increment(user_id)
  end
end

Before prompting callback

class MyAgent < ActiveAgent::Base
  before_prompt :load_context

  def load_context
    @user_data = User.find(params[:user_id])
  end
end

After prompting with condition

class MyAgent < ActiveAgent::Base
  after_prompt :log_response, if: :production?

  def log_response
    Logger.info("Generated response: #{context.messages.last}")
  end
end

Around embedding for timing

class MyAgent < ActiveAgent::Base
  around_embed :measure_time

  def measure_time
    start = Time.now
    yield
    Rails.logger.info("Embedding took #{Time.now - start}s")
  end
end

Prepending and skipping callbacks

class MyAgent < ActiveAgent::Base
  prepend_before_prompt :urgent_check  # Runs first
  before_prompt :normal_check          # Runs second

  skip_after_prompt :log_response      # Removes inherited callback
end

Defined Under Namespace

Modules: ClassMethods