Project

action_ai

0.0
The project is in a healthy, maintained state
AI on Rails. Compose, run, and test AI prompts using the familiar controller/view pattern.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
 Dependencies
 Project Readme

Action AI – Easy AI prompt execution and testing

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.

Sending prompts

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
  model "gpt-6.1-sol"

  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

Configuration

Your agent class uses the full RubyLLM::Agent configuration DSL directly. You never need to define or reference a RubyLLM::Agent subclass yourself; just call model, instructions, tools, schema, and the other RubyLLM::Agent class macros right on your Action AI agent:

class Generator < ApplicationAI
  model "gpt-6.1-sol"
  instructions "You are a concise support assistant."
  tools SearchDocs, LookupAccount

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

If you declare inputs, use ActionAI::Parameterized to supply them at call time; the parameters given to with are forwarded as the agent’s runtime inputs:

class Generator < ApplicationAI
  inputs :workspace

  instructions { "You are helping #{workspace.name}" }
end

Generator.with(workspace:).code("Parse CSV", :ruby)

Subclasses inherit their parent’s RubyLLM agent configuration and can extend or override it, the same way RubyLLM::Agent subclasses do:

class ApplicationAI < ActionAI::Agent
  model "gpt-6-luna", provider: :openai
end

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

The Agent class has a few settings unrelated to the RubyLLM agent DSL that are specified on the class level. Here’s an example:

ActionAI::Agent.execute_later_queue_name = :ai_agents
  • logger — the logger is used for generating information on prompt execution if available. Can be set to nil for no logging. Compatible with both Ruby’s own Logger and Log4r loggers.

  • execution_job — The job class used with later. Agents can set this to use a custom execution job. Defaults to ActionAI::ExecutionJob.

  • execute_later_queue_name — The queue name used by later with the default execution_job. Agents can set this to use a custom queue name.

Structured output (data schemas)

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

.schema on ActiveModel models

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.

Active Record associations are included as nested schemas via object/array. To prevent unnescessary nesting or circular dependencies, the schema will include associations registered for _nested attributes_ (via accepts_nested_attributes_for) only.

returns in agent actions

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 Strong Parameters.

  3. Construct a model instance accessible via #object.

class Extractor < ApplicationAI
  def person(text)
    @text = text

    returns Person do |params|
      params.permit(:name, :age)
    end
  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] do |params|
      params.permit(:name, :age)
    end
  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.

Custom schemas

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

Download and installation

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

$ gem install action_ai

License

Action AI is released under the MIT license: