Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
4.6 KB
Raw Blame
# Per-family overrides for the built-in AI prompts, editable from
# /settings/ai_prompts so tuning them no longer needs a fork + redeploy.
#
# Every override is stored in one jsonb column and resolved at the point of use
# (`Assistant::Configurable#default_instructions` and the four provider
# `instructions` methods) as `family&.ai_prompt(key) || <hardcoded default>`.
# A blank value is deleted on save, so clearing a field *is* resetting it.
module Family::AiPromptable
  extend ActiveSupport::Concern

  # Overrides are sent to the provider on every call, so an unbounded value is a
  # cost problem, not just a storage one. Generous next to the ~4KB defaults.
  MAX_LENGTH = 20_000

  # A custom OpenAI-compatible endpoint gets `simple_instructions`; native
  # OpenAI gets `detailed_instructions`. One override key replaces both, so the
  # editor has to pre-fill the variant this deployment sends. Otherwise editing
  # it swaps a small local model's terse rules for a prompt written for GPT-4.
  # Mirrors how Provider::Registry picks the endpoint.
  def self.custom_openai_provider?
    Provider::Openai.custom_endpoint?(ENV["OPENAI_URI_BASE"].presence || Setting.openai_uri_base)
  end

  # Each key's stock text, lazily. Constructing a provider class with
  # `family: nil` is exactly what returns the hardcoded default, so no prompt
  # string is duplicated here.
  DEFAULTS = {
    chat_system: -> { Assistant::Configurable::STATIC_INSTRUCTIONS },
    categorizer_openai: -> { Provider::Openai::AutoCategorizer.new(nil, custom_provider: custom_openai_provider?).instructions },
    categorizer_anthropic: -> { Provider::Anthropic::AutoCategorizer.new(nil, model: "").instructions },
    merchant_openai: -> { Provider::Openai::AutoMerchantDetector.new(nil, model: "", transactions: [], user_merchants: [], custom_provider: custom_openai_provider?).instructions },
    merchant_anthropic: -> { Provider::Anthropic::AutoMerchantDetector.new(nil, model: "", transactions: [], user_merchants: []).instructions },
    # The visible first chat message of "Dig in with AI", not instructions.
    insight_dig_in: -> { I18n.t("insights.dig_in.prompt") }
  }.freeze

  KEYS = DEFAULTS.keys.freeze

  # The generic (custom-endpoint) path also asks for these keys in a
  # per-request message an override cannot replace, so a missing one rarely
  # breaks parsing by itself. It stays the cheapest signal that someone deleted
  # the example block, so the editor says so instead of rejecting the save.
  # Anthropic takes its wrapper key from the tool schema and native OpenAI from
  # a strict response schema, so neither belongs here.
  WRAPPER_KEYS = { categorizer_openai: "categorizations", merchant_openai: "merchants" }.freeze

  # Attribute names generated by `store_accessor` below — the form fields and the
  # controller's permitted params.
  FIELDS = KEYS.map { |key| :"ai_prompt_#{key}" }.freeze

  included do
    store_accessor :ai_prompt_overrides, *KEYS, prefix: :ai_prompt

    # Assigned rather than mutated in place so the jsonb attribute is
    # unambiguously dirty when only blanks were submitted (a reset).
    before_save { self.ai_prompt_overrides = ai_prompt_overrides.to_h.compact_blank }

    validate :validate_ai_prompt_overrides_schema

    validates *FIELDS,
      length: {
        maximum: MAX_LENGTH,
        message: ->(_object, _data) {
          I18n.t("errors.messages.too_long", count: MAX_LENGTH.to_fs(:delimited))
        }
      },
      allow_blank: true
  end

  # The family's override for `key`, or nil when it runs the default.
  def ai_prompt(key)
    ai_prompt_overrides[key.to_s].presence
  end

  def ai_prompt_default(key)
    DEFAULTS.fetch(key.to_sym).call
  end

  # True when this deployment sends a prompt variant carrying a wrapper key and
  # the family's override dropped it. Advisory only, never a validation error.
  def ai_prompt_format_risk?(key)
    wrapper = WRAPPER_KEYS[key.to_sym]
    return false unless wrapper && Family::AiPromptable.custom_openai_provider?

    override = ai_prompt(key)
    override.present? && override.exclude?(wrapper)
  end

  private
    def validate_ai_prompt_overrides_schema
      unless ai_prompt_overrides.is_a?(Hash)
        errors.add(:ai_prompt_overrides, :invalid)
        return
      end

      unknown_keys = ai_prompt_overrides.keys.map(&:to_s) - KEYS.map(&:to_s)
      if unknown_keys.any?
        errors.add(:ai_prompt_overrides, :invalid)
      end

      ai_prompt_overrides.each do |key, val|
        if val.nil?
          next
        elsif !val.is_a?(String)
          errors.add(:"ai_prompt_#{key}", :invalid)
        elsif val.include?("\u0000")
          errors.add(:"ai_prompt_#{key}", :invalid)
        end
      end
    end
end