Skip to content

Active Agent

ActiveAgent extends Rails MVC to AI interactions. Build intelligent agents using familiar patterns—controllers, actions, callbacks, and views.

Quick Example

ruby
class SupportAgent < ApplicationAgent
  generate_with :openai, model: "gpt-4o-mini"

  # @return [ActiveAgent::Generation]
  def help
    prompt(params[:question])
  end
end
md
You are a helpful support agent.

Usage:

ruby
response = SupportAgent.with(question: "How do I reset my password?").help.generate_now
# response.message.content  #=> "To reset your password..."
Response Example

activeagent/test/docs/framework_examples_test.rb:30

ruby
#<ActiveAgent::Providers::Common::Responses::Prompt {
  "context": {
    "model": "gpt-4o-mini",
    "messages": [
      "How do I reset my password?"
    ],
    "trace_id": "8fa64b8a-724e-49c7-806a-2a957f972972",
    "instructions": "You are a helpful support agent."
  },
  "raw_request": {
    "model": "gpt-4o-mini",
    "instructions": "You are a helpful support agent.",
    "input": "How do I reset my password?"
  },
  "raw_response": {
    "id": "resp_0cdf33b61f2cdd4c0068fe72e379f481958d649b83b8d56d02",
    "created_at": 1761506019,
    "instructions": "You are a helpful support agent.",
    "model": "gpt-4o-mini-2024-07-18",
    "object": "response",
    "output": [
      {
        "id": "msg_0cdf33b61f2cdd4c0068fe72e49580819585242b75c94b4bd0",
        "content": [
          {
            "text": "To reset your password, follow these steps:\n\n1. **Go to the login page** of the website or service you are trying to access.\n2. Look for a link that says **\"Forgot Password?\"** or **\"Reset Password.\"** Click on it.\n3. Enter your **email address** or username associated with your account.\n4. Check your email for a password reset link. Be sure to check your spam or junk folder if you don’t see it.\n5. Click on the link in the email and follow the instructions to create a new password.\n6. Log in with your new password.\n\nIf you encounter any issues, consider reaching out to the customer support team of the service for further assistance.",
            "type": "output_text"
          }
        ],
        "role": "assistant",
        "status": "completed",
        "type": "message"
      }
    ],
    "parallel_tool_calls": true,
    "temperature": 1.0,
    "tool_choice": "auto",
    "top_p": 1.0,
    "background": false,
    "service_tier": "default",
    "status": "completed",
    "text": {
      "format": {
        "type": "text"
      },
      "verbosity": "medium"
    },
    "top_logprobs": 0,
    "truncation": "disabled",
    "usage": {
      "input_tokens": 25,
      "input_tokens_details": {
        "cached_tokens": 0
      },
      "output_tokens": 146,
      "output_tokens_details": {
        "reasoning_tokens": 0
      },
      "total_tokens": 171
    },
    "billing": {
      "payer": "developer"
    },
    "store": true
  },
  "usages": [
    "#<ActiveAgent::Providers::Common::Usage {\n  \"input_tokens\": 25,\n  \"output_tokens\": 146,\n  \"total_tokens\": 171,\n  \"cached_tokens\": 0,\n  \"reasoning_tokens\": 0,\n  \"provider_details\": {\n    \"input_tokens_details\": {\n      \"cached_tokens\": 0\n    },\n    \"output_tokens_details\": {\n      \"reasoning_tokens\": 0\n    }\n  }\n}>"
  ],
  "messages": [
    {
      "role": "user",
      "content": "How do I reset my password?"
    },
    {
      "role": "assistant",
      "content": "To reset your password, follow these steps:\n\n1. **Go to the login page** of the website or service you are trying to access.\n2. Look for a link that says **\"Forgot Password?\"** or **\"Reset Password.\"** Click on it.\n3. Enter your **email address** or username associated with your account.\n4. Check your email for a password reset link. Be sure to check your spam or junk folder if you don’t see it.\n5. Click on the link in the email and follow the instructions to create a new password.\n6. Log in with your new password.\n\nIf you encounter any issues, consider reaching out to the customer support team of the service for further assistance."
    }
  ]
}>

Agent Oriented Programming

ActiveAgent applies Agent Oriented Programming (AOP) to Rails—a paradigm where agents are the primary building blocks. Agents combine behavior (instructions), state (context), and capabilities (tools) into autonomous components.

Programming Paradigm Shift:

ConceptObject-OrientedAgent-Oriented
UnitObjectAgent
Parametersmessage, args, blockprompt, context, tools
Computationmethod, send, returnperform, generate, response
Stateinstance variablesprompt context
Flowmethod callsprompt-response cycles
Constraintscoded logicwritten instructions

Write instructions instead of algorithms. Define context instead of managing state. Coordinate through prompts instead of method chains.

Understanding Agents

Agents mirror how users interact with systems—they have identity, behavior, and goals:

AspectUserAgent
WhoPersonaArchetype
BehaviorStoriesInstructions
StateScenarioContext
WhatObjectiveGoal
HowActionsTools

When you define an agent, you create a specialized participant that interacts with your application through prompts, maintains conversation context, and uses tools to accomplish objectives.

Core Architecture

ActiveAgent-Controllers

Three Key Objects:

  • Agent (Controller) - Manages lifecycle, defines actions, configures providers
  • Generation (Request Proxy) - Coordinates execution, holds configuration, provides synchronous/async methods. Created by invocation, it's lazy—execution doesn't start until you call .prompt_now, .embed_now, or .prompt_later.
  • Response (Result) - Contains messages, metadata, and normalized usage statistics (see Usage Statistics). Returned after Generation executes.

Request-Response Lifecycle:

  1. Invocation → Generation object created with parameters
  2. Callbacksbefore_generation hooks execute
  3. Action → Agent method called (optional for direct invocations)
  4. Prompt/Embedprompt() or embed() configures request context
  5. Template → ERB view renders (if template exists)
  6. Request → Provider request built with messages, tools, options
  7. Execution → API called (with streaming/tool execution if configured)
  8. Processing → Response parsed, messages extracted
  9. Callbacksafter_generation hooks execute
  10. Return → Response object with message and metadata

Three Invocation Patterns:

ruby
# Direct - no action method needed
Agent.prompt(message: "Hello").generate_now
ruby
# Parameterized - passes params to action
Agent.with(name: "Alice").greet.generate_now
ruby
# Action-based - traditional positional arguments
Agent.greet("Alice").generate_now

See Generation for complete execution details.

MVC Mapping

ActiveAgent maps Rails MVC patterns to AI interactions:

Model: Prompt Interface

The prompt and embed interfaces are runtime configuration objects built inside agent actions. Calling prompt(message: "...", tools: [...]) or embed(input: "...") returns a Generation object configured with messages, tools, response_format, temperature, and other parameters that define the AI request.

Use these methods in your action methods to build the request context before execution. See Messages for complete details.

View: Message Templates

ERB templates render instructions, messages, and schemas for AI requests. Templates are optional—you can pass strings or hashes directly.

  • Instructions - System prompts that guide agent behavior (.text.erb, .md.erb)
  • Messages - User/assistant conversation content (.text.erb, .md.erb, .html.erb)
  • Schemas - JSON response format definitions (.json)

See Instructions, Messages, and Structured Output for template patterns.

Controller: Agents

Agents are controllers with actions (public methods), callbacks (before_generation, after_generation), and provider configuration (generate_with, embed_with).

Actions call prompt() or embed() to configure requests. Callbacks manage context and side effects. Configuration sets defaults for model, temperature, and other options. See Agents for complete patterns.

Integration Points

ActiveAgent integrates with Rails features and AI capabilities:

  • Providers - Swap AI services (OpenAI, Anthropic, Ollama, OpenRouter)
  • Instructions - System prompts from templates or strings
  • Callbacks - Lifecycle hooks for context and logging
  • Tools - Agent methods as AI-callable functions
  • Structured Output - JSON schemas for response format
  • Streaming - Real-time response updates
  • Messages - Multimodal conversation context
  • Embeddings - Vector generation for semantic search

Next Steps

Start Here:

  • Getting Started - Build your first agent (step-by-step tutorial)
  • Agents - Deep dive into agent patterns and lifecycle
  • Actions - Define capabilities with messages, tools, and schemas

Core Features:

  • Generation - Synchronous and asynchronous execution
  • Instructions - System prompts and behavior guidance
  • Messages - Conversation context with multimodal support
  • Providers - OpenAI, Anthropic, Ollama, OpenRouter configuration

Advanced:

Rails Integration:

Examples: