Skip to content

Repository files navigation

Action AI is a framework for designing AI interaction layers. These layers are used to consolidate prompt generation and execution in one place, instead of scattering provider calls across controllers, jobs, and models.

Action AI is in essence a wrapper around Action Controller and the RubyLLM gem. It provides a way to make AI prompts using templates in the same way that Action Controller renders views using templates.

The architecture is intentionally modeled after Action Mailer: class-level actions, view-backed templates, and lazy execution. Action AI rebuilds that shape for AI interactions rather than building an unrelated API from scratch.

The framework works by initializing any instance variables you want to be available in the prompt template. Like render in Action Controller, the implicit ask will be triggered automatically at the end of the action unless you have already called it.

This can be as simple as:

class Generator < ApplicationAI
  default model: "gpt-4o"

  def code(task, language)
    @task     = task
    @language = language
  end
end

If you need to customize the prompt execution (e.g., pass options or a custom prompt), you can call ask explicitly:

def run(spec_file)
  ask "Run the attached spec", with: spec_file
end

After the action method completes, the framework will automatically:

  1. Render the prompt from the corresponding template (e.g., app/ai/prompts/generator/code.erb)

  2. Send it to the configured AI model via ask

  3. Return an ActionAI::Interaction object

The prompt text is created by using an Action View template (regular ERB) that has the instance variables that are declared in the agent action.

So the corresponding template for the code method above could look like this:

You are an expert <%= @language.to_s.camelize %> developer.
Write clean, well-commented code for the following task:

<%= @task %>

If the task description was “Parse a CSV file and return unique values”, the rendered prompt would look like this:

You are an expert Ruby developer.
Write clean, well-commented code for the following task:

Parse a CSV file and return unique values

In order to execute prompts, you simply call the method and then call content to get the result or just run on the return value.

Calling the method returns a RubyLLM Message object:

prompt = Generator.code("Parse CSV and dedupe", :ruby) # => Returns a RubyLLM::Message object
prompt.run                                             # => executes the prompt

Or you can just chain the methods together like:

Generator.code("Parse CSV and dedupe", :ruby).content  # Returns AI's response for the prompt

You can also chain multiple agent actions to compose a small workflow before reading the final response:

class WorkflowAgent < ApplicationAI
  def collect(topic)
    @topic = topic
    ask "Collect #{@topic}"
  end

  def refine(style:)
    ask "Refine #{@topic} as #{style}"
  end
end

WorkflowAgent.collect("release notes").refine(style: "bullet list").content
# => collected release notes refined as bullet list

It is possible to set default values that will be used in every method in your Action AI Agent class. To implement this functionality, you just call the public class method default which you get for free from ActionAI::Agent. This method accepts a Hash as the parameter. You can use any options supported by RubyLLM::Chat, such as :provider and :model. Finally, it is also possible to pass in a Proc that will get evaluated when it is needed.

Note that every value you set with this method will get overwritten if you use the same key in your agent method.

Example:

class Generator < ApplicationAI
  default model: proc { Current.user.preferred_model }
end

The Agent class has the full list of configuration options. Here’s an example:

ActionAI::Agent.default_options = {
  provider: :openai,
  model: "gpt-4o-mini"
}

Action AI can instruct the model to return structured JSON that maps directly to an ActiveModel model. Two features cooperate to make this work:

Any model that includes ActiveModel::API automatically gains a .schema class method that returns a Schematist::Schema instance derived from the model’s attribute types.

class Person
  include ActiveModel::Model
  include ActiveModel::Attributes

  attribute :name,  :string
  attribute :age,   :integer
  attribute :score, :float
end

Person.schema                         # => a Schematist::Schema instance
Person.schema.new.to_json_schema      # => {name: "Person", schema: {...}}

Supported type mappings:

  • :string, :immutable_string, :text → JSON string

  • :integer, :big_integer → JSON integer

  • :float, :decimal, :big_decimal → JSON number

  • :boolean → JSON boolean

  • :date, :datetime, :time → JSON string with format set to +“date”+, +“date-time”+, or +“time”+ respectively

  • :binary → JSON string with contentEncoding set to +“base64”+

Other types are not included in the schema.

Call +returns ModelClass+ inside an action method to declare the expected return type. Action AI will:

  1. Configure the chat to request output matching the model’s JSON schema (+chat.with_schema ModelClass.schema+).

  2. Decorate the resulting RubyLLM::Message with #object (a model instance).

class Extractor < ApplicationAI
  def person(text)
    @text = text
    returns Person
  end
end

result = Extractor.person("Alice is 30 years old")
result.content  # => '{"name":"Alice","age":30}'
result.parsed   # => {"name" => "Alice", "age" => 30}
result.object   # => #<Person name="Alice" age=30>

Pass the class wrapped in an array to declare an array return type:

class Extractor < ApplicationAI
  def people(text)
    @text = text
    returns [Person]
  end
end

result = Extractor.people("Alice is 30 and Bob is 25")
result.content  # => '[{"name":"Alice","age":30},{"name":"Bob","age":25}]'
result.parsed   # => [{"name" => "Alice", "age" => 30}, {"name" => "Bob", "age" => 25}]
result.object   # => [#<Person name="Alice" age=30>, #<Person name="Bob" age=25>]

The schema is built from the model’s declared attributes and cached.

If an inferred schema is not sufficient, define a Schematist::Schema subclass under app/schemas with the model’s full class name followed by Schema. Custom schemas are looked up first; models without a matching class continue to use the inferred schema.

# app/schemas/person_schema.rb
class PersonSchema < ActionAI::Schema
  string :name
  integer :age, minimum: 0
end

For namespaced models, mirror the namespace in app/schemas:

# app/schemas/admin/person_schema.rb
class Admin::PersonSchema < ActionAI::Schema
  string :name
end

The latest version of Action AI can be installed with RubyGems:

$ gem install action_ai

Action AI is released under the MIT license:

About

Action AI is a framework for designing AI interaction layers for Rails.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Contributors

Languages