Class: ActiveAgent::Base Abstract

Inherits:
AbstractController::Base
  • Object
show all
Includes:
AbstractController::AssetPaths, AbstractController::Caching, AbstractController::Callbacks, AbstractController::Helpers, AbstractController::Logger, AbstractController::Rendering, AbstractController::Translation, Callbacks, Delegation, Observers, Parameterized, Previews, Provider, Queueing, Rescue, Streaming, Tooling, View
Defined in:
lib/active_agent/base.rb

Overview

This class is abstract.

Provides AI-powered agents with prompt generation, tool calling, and conversation management.

Examples:

Basic agent

class MyAgent < ActiveAgent::Base
  generate_with :openai, model: "gpt-4"

  def greet
    prompt instructions: "Greet the user warmly"
  end
end

Constant Summary collapse

PROTECTED_OPTIONS =
%i[exception_handler stream_broadcaster tools_function]
PROTECTED_IVARS =
AbstractController::Rendering::DEFAULT_PROTECTED_INSTANCE_VARIABLES + [ :@_action_has_layout ]

Constants included from Provider

Provider::PROVIDER_SERVICE_NAMES_REMAPS

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from View

#_prefixes, #embed_view_input, #prompt_view_instructions, #prompt_view_message, #prompt_view_schema

Methods included from Tooling

#tools_function

Methods included from Rescue

#handle_exceptions

Methods included from Delegation

#delegation_ledger, #delegation_ledger_for, #delegation_ledgers, #perform_delegation

Constructor Details

#initializeBase

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns a new instance of Base.



172
173
174
175
176
# File 'lib/active_agent/base.rb', line 172

def initialize # :nodoc:
  super
  self.prompt_options = (self.class.prompt_options&.deep_dup || {}).except(:trace_id)
  self.embed_options  = (self.class.embed_options&.deep_dup  || {}).except(:trace_id)
end

Instance Attribute Details

#agent_nameString

Agent name used as a path for view lookup.

Returns:

  • (String)

    agent name or "anonymous" for anonymous agents



181
182
183
# File 'lib/active_agent/base.rb', line 181

def agent_name
  @agent_name ||= self.class.anonymous? ? "anonymous" : self.class.name.underscore
end

#embed_optionsHash

Action-level embed options merged with agent embed options.

Returns:

  • (Hash)


169
# File 'lib/active_agent/base.rb', line 169

attr_internal :embed_options

#prompt_optionsHash

Action-level prompt options merged with agent prompt options.

Returns:

  • (Hash)


164
# File 'lib/active_agent/base.rb', line 164

attr_internal :prompt_options

Class Method Details

.default(value = nil) ⇒ Hash Also known as: default_params=

Sets default parameters applied to all actions unless overridden.

Examples:

default temperature: 0.7, max_tokens: 1000

Parameters:

  • value (Hash, nil) (defaults to: nil)

    parameters to merge, or nil to return current defaults

Returns:

  • (Hash)


87
88
89
90
# File 'lib/active_agent/base.rb', line 87

def default(value = nil)
  self.default_params = default_params.merge(value).freeze if value
  default_params
end

.embed_with(provider_reference, **agent_options) ⇒ void

This method returns an undefined value.

Configures embedding provider and options for embedding generation.

Examples:

embed_with :openai, model: "text-embedding-3-large"

Parameters:

  • provider_reference (Symbol, String)

    embedding provider (:openai, :anthropic, etc.)

  • agent_options (Hash)

    configuration options for embedding generation



128
129
130
131
132
133
134
135
# File 'lib/active_agent/base.rb', line 128

def self.embed_with(provider_reference, **agent_options)
  self.embed_provider = provider_reference

  global_options    = provider_config_load(provider_reference)
  inherited_options = self.embed_options || {}

  self.embed_options = global_options.merge(inherited_options).merge(agent_options)
end

.generate_with(provider_reference, **agent_options) ⇒ void

This method returns an undefined value.

Configures generation provider and options for prompt generation.

Options are merged with global provider config and inherited parent class options. Instructions are never inherited from parent classes.

Examples:

generate_with :openai, model: "gpt-4", temperature: 0.7

Parameters:

  • provider_reference (Symbol, String)

    generation provider (:openai, :anthropic, etc.)

  • agent_options (Hash)

    configuration options shared across actions



105
106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'lib/active_agent/base.rb', line 105

def self.generate_with(provider_reference, **agent_options)
  self.prompt_provider = provider_reference

  global_options    = provider_config_load(provider_reference)
  inherited_options = (self.prompt_options || {}).except(:instructions) # Don't inherit instructions from parent

  # Different Service, different APIs — discard all inherited options
  # to prevent parent provider config (host, api_key, etc.) leaking through
  if global_options[:service] != inherited_options[:service]
    inherited_options = {}
  end

  self.prompt_options = global_options.merge(inherited_options).merge(agent_options)
end

Instance Method Details

#action_methodsObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



296
297
298
# File 'lib/active_agent/base.rb', line 296

def action_methods
  super - ActiveAgent::Base.public_instance_methods(false).map(&:to_s) - [ action_name ]
end

#controller_pathObject



159
# File 'lib/active_agent/base.rb', line 159

alias_method :controller_path, :agent_name

#embed(input = nil, **options) ⇒ void

This method returns an undefined value.

Merges action-level parameters into embedding context.

Examples:

With direct input

embed "Text to embed", model: "text-embedding-3-large"

With template

embed locals: { text: "Custom text" }

Parameters:

  • input (String, Array<String>, nil) (defaults to: nil)

    text to embed

  • options (Hash)

    parameters to merge into embedding context



236
237
238
239
# File 'lib/active_agent/base.rb', line 236

def embed(input = nil, **options)
  new_options = { input: }.compact_blank.merge!(options)
  embed_options.merge!(new_options)
end

#loggerLogger?

Logger instance for agent operations.

Defaults to Rails.logger when used in Rails applications. Must conform to Log4r or Ruby Logger interface.

Returns:

  • (Logger, nil)


67
# File 'lib/active_agent/base.rb', line 67

cattr_accessor :logger

#preview_promptString, Hash

Generates a preview of the prompt without executing generation.

Useful for debugging and inspecting the final prompt that would be sent to the provider, including rendered templates and merged parameters.

Returns:

  • (String, Hash)

    preview format depends on provider implementation

Raises:

  • (RuntimeError)

    if no prompt provider is configured



269
270
271
272
273
274
275
# File 'lib/active_agent/base.rb', line 269

def preview_prompt
  fail "Prompt Provider not Configured" unless prompt_provider_klass

  parameters = prepare_prompt_parameters

  prompt_provider_klass.new(**parameters).preview
end

#process(method_name, *args, **kwargs) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Processes an agent action with ActiveSupport::Notifications instrumentation.

Actions are triggered externally via Agent.action_name.generate_now or internally through tool calls during AI generation workflows.

Parameters:

  • method_name (Symbol, String)

    action method to process

  • args (Array)
  • kwargs (Hash)


195
196
197
198
199
200
201
# File 'lib/active_agent/base.rb', line 195

def process(method_name, *args, **kwargs)
  payload = { agent: self.class.name, action: method_name, args:, kwargs: }

  ActiveSupport::Notifications.instrument("process.active_agent", payload) do
    super
  end
end

#process_embedActiveAgent::Providers::Response

Executes embedding generation using configured provider and options.

Templates are rendered as late as possible to allow local overrides.

Returns:

  • (ActiveAgent::Providers::Response)

Raises:

  • (RuntimeError)

    if no embed provider is configured



283
284
285
286
287
288
289
290
291
292
293
# File 'lib/active_agent/base.rb', line 283

def process_embed
  fail "Embed Provider not Configured" unless embed_provider_klass

  run_callbacks(:generation) do
    run_callbacks(:embedding) do
      parameters = prepare_embed_parameters

      embed_provider_klass.new(**parameters).embed
    end
  end
end

#process_promptActiveAgent::Providers::Response Also known as: process_prompt!

Executes prompt generation using configured provider and options.

Triggered by generate_now or generate_later workflows. Templates are rendered as late as possible to allow local overrides.

Returns:

  • (ActiveAgent::Providers::Response)

Raises:

  • (RuntimeError)

    if no prompt provider is configured



248
249
250
251
252
253
254
255
256
257
258
# File 'lib/active_agent/base.rb', line 248

def process_prompt
  fail "Prompt Provider not Configured" unless prompt_provider_klass

  run_callbacks(:generation) do
    run_callbacks(:prompting) do
      parameters = prepare_prompt_parameters

      prompt_provider_klass.new(**parameters).prompt
    end
  end
end

#prompt(*messages, **options) ⇒ void

This method returns an undefined value.

Merges action-level parameters into prompt context.

Processing is deferred until execution to allow local overrides.

Examples:

def my_action
  prompt "User message", temperature: 0.8, instructions: "Be creative"
end

Parameters:

  • messages (Array<String, Hash>)

    message strings or hashes to add to conversation

  • options (Hash)

    parameters to merge into prompt context



215
216
217
218
219
220
221
222
223
# File 'lib/active_agent/base.rb', line 215

def prompt(*messages, **options)
  # Extract message/messages from options and add to messages array
  messages += options.extract!(:message, :messages).values.flatten.compact

  # Extract image and document attachments
  messages += options.extract!(:image, :document).map { |k, v| { k => v } }

  prompt_options.merge!({ messages: }.compact_blank.merge!(options))
end