50
  E   ˆl–Ü4ý('ÜZÔâ€vàZ¸ÓJbÑ¿�þC+dYÆÈÜ�¸Ûï¶ÈŸÕƒx{Ô_�uÐb&=LyZËcõÈÓ \    # Copyright (C) 2012-2026 Zammad Foundation, https://zammad-foundation.org/

class AI::Provider
  # Model listing for the providers whose endpoint can enumerate its models, and the single place
  # where a model's capabilities are derived when the provider does not report them itself.
  #
  # Including this declares supports_model_listing?; the provider still has to implement
  # .models(config, related_object:) with its own endpoint and payload.
  module Concerns::ListsModels
    extend ActiveSupport::Concern

    # Listing models is a metadata read, not inference, so it does not get the generous AI
    # timeouts: an admin waiting for the dropdown has to see a failure quickly instead.
    MODEL_LIST_TIMEOUT_OPTIONS = {
      read_timeout:  ENV.fetch('ZAMMAD_HTTP_AI_MODEL_LIST_TIMEOUT', 30).to_i,
      total_timeout: ENV.fetch('ZAMMAD_HTTP_AI_MODEL_LIST_TIMEOUT', 30).to_i,
    }.freeze

    # Ids of models that are neither chat nor embedding models (images, audio, moderation,
    # reranking, dedicated OCR endpoints). They end up without any capability, so a caller
    # filtering for one skips them instead of offering a model that cannot answer a prompt.
    OTHER_MODEL_ID_PATTERN = %r{
      dall-e | gpt-image | \Asora | \Atts | -tts | whisper | transcribe | audio | realtime
      | moderation | rerank | \Aocr | -ocr | \A(?: babbage | davinci )-
    }xi

    # Ids of embedding models. Only consulted when the provider reports no capabilities, and
    # deliberately narrow: a false positive would hide a chat model from the chat dropdown.
    EMBEDDING_MODEL_ID_PATTERN = %r{
      embed | (?: \A | [/-] ) (?: bge | gte | e5 | minilm | paraphrase )
    }xi

    # Ids of models that accept images. Providers reporting vision themselves never get here.
    VISION_MODEL_ID_PATTERN = %r{
      vision | llava | moondream | minicpm-v | pixtral | gemma3 | -vl[-.:\d]
      | \Agpt-(?: 4o | 4\.1 | 4-turbo | 5 ) | \Ao[34](?: - | \z )
      | \Aclaude-(?: 3 | 4 | 5 | opus | sonnet | haiku )
    }xi

    # A module rather than a `class_methods` block, because the listing is class level throughout
    # (like ping!) and its helpers do not fit into one block.
    module ClassMethods
      def supports_model_listing?
        true
      end

      private

      # The listing request itself, so a provider only has to bring its URL and its
      # authentication. Logged only on error like the other config time requests: the dialog may
      # fetch the list repeatedly, which would otherwise flood the admin HTTP log.
      def model_list_response(url, params: {}, related_object: nil, **)
        UserAgent.get(
          url,
          params,
          {
            **MODEL_LIST_TIMEOUT_OPTIONS,
            verify_ssl: true,
            json:       true,
            log:        log_options(only_on_error: true, related_object:),
            **,
          },
        )
      end

      # A normalized model descriptor. Fields the provider does not report - or reports as
      # something other than the promised type - stay nil instead of being guessed, so a caller
      # can tell "unknown" from a real value.
      #
      # No display name, deliberately: the id is what every consumer renders.
      #
      # @param capabilities [Array<Symbol>, NilClass] as reported by the provider; an empty or
      #   absent list falls back to the id heuristics (e.g. Mistral flags chat and vision, but
      #   leaves an embedding model without any capability at all).
      #
      # @return [Hash] the normalized descriptor
      def model_descriptor(id:, capabilities: nil, embedding_input_limit: nil, embedding_size: nil)
        capabilities = capabilities.presence || capabilities_from_id(id)
        embedding    = capabilities.include?(:embedding)

        {
          id:,
          capabilities:,
          # Both sizes describe an embedding model only, and are reported for one alone: the
          # context window of a chat model has no consumer, and the embedding len