Module: LLM::ActiveRecord::ActsAsLLM

Defined in:
lib/llm/active_record/acts_as_llm.rb

Overview

ActiveRecord integration for persisting LLM::Context state.

This wrapper maps model columns onto provider selection, model selection, usage accounting, and serialized context data while leaving application- specific concerns such as credentials, associations, and UI shaping to the host app.

Context state can be stored as a JSON string (‘format: :string`, the default) or as a structured object (`format: :json` / `:jsonb`) for databases such as PostgreSQL that can persist JSON natively. `:json` and `:jsonb` expect a real JSON column type with ActiveRecord handling JSON typecasting for the model.

Defined Under Namespace

Modules: Hooks, InstanceMethods

Constant Summary collapse

EMPTY_HASH =
{}.freeze
DEFAULT_USAGE_COLUMNS =
{
  input_tokens: :input_tokens,
  output_tokens: :output_tokens,
  total_tokens: :total_tokens
}.freeze
DEFAULTS =
{
  provider_column: :provider,
  model_column: :model,
  data_column: :data,
  format: :string,
  usage_columns: DEFAULT_USAGE_COLUMNS,
  provider: EMPTY_HASH,
  context: EMPTY_HASH
}.freeze

Instance Method Summary collapse

Instance Method Details

#acts_as_llm(options = EMPTY_HASH) ⇒ void

This method returns an undefined value.

Installs the ‘acts_as_llm` wrapper on an ActiveRecord model.

Parameters:

  • options (Hash) (defaults to: EMPTY_HASH)

Options Hash (options):

  • :format (Symbol)

    Storage format for the serialized context. Use ‘:string` for text columns, or `:json` / `:jsonb` for structured JSON columns with ActiveRecord JSON typecasting enabled.



56
57
58
59
60
61
62
# File 'lib/llm/active_record/acts_as_llm.rb', line 56

def acts_as_llm(options = EMPTY_HASH)
  options = DEFAULTS.merge(options)
  usage_columns = DEFAULT_USAGE_COLUMNS.merge(options[:usage_columns] || EMPTY_HASH)
  class_attribute :llm_plugin_options, instance_accessor: false, default: DEFAULTS unless respond_to?(:llm_plugin_options)
  self.llm_plugin_options = options.merge(usage_columns: usage_columns.freeze).freeze
  extend Hooks
end