Class: RubyLLM::Agents::Pipeline::Middleware::Tenant

Inherits:
Base
  • Object
show all
Defined in:
lib/ruby_llm/agents/pipeline/middleware/tenant.rb

Overview

Resolves tenant context from options and applies API configuration.

This middleware extracts tenant information from the context options, sets the tenant_id, tenant_object, and tenant_config on the context, and applies any tenant-specific API keys to RubyLLM.

Supports three formats:

  • Object with llm_tenant_id method (recommended for ActiveRecord models)

  • Hash with :id key (simple/legacy format)

  • nil (no tenant - single-tenant mode)

API keys are configured via:

  • RubyLLM.configuration (set via initializer or environment variables)

  • Tenant object’s llm_api_keys method (for per-tenant overrides)

Examples:

With ActiveRecord model

# Model uses llm_tenant DSL
class Organization < ApplicationRecord
  include RubyLLM::Agents::LLMTenant
  llm_tenant id: :slug, api_keys: { openai: :openai_key }
end

# Pass tenant to agent
MyAgent.call(query: "test", tenant: organization)

With hash

MyAgent.call(query: "test", tenant: { id: "org_123" })

Without tenant

MyAgent.call(query: "test")  # Single-tenant mode

Constant Summary

Constants inherited from Base

Base::LOG_TAG

Instance Method Summary collapse

Methods inherited from Base

#initialize

Constructor Details

This class inherits a constructor from RubyLLM::Agents::Pipeline::Middleware::Base

Instance Method Details

#call(context) ⇒ Context

Process tenant resolution and API key application

Parameters:

  • context (Context)

    The execution context

Returns:

  • (Context)

    The context with tenant fields populated



43
44
45
46
47
48
49
50
# File 'lib/ruby_llm/agents/pipeline/middleware/tenant.rb', line 43

def call(context)
  trace(context) do
    resolve_tenant!(context)
    ensure_tenant_record!(context)
    apply_api_configuration!(context)
    @app.call(context)
  end
end