Sha256: b2ac558894651e2ccaa1c4068233451a4b70636de20a0586665b36204d9048f1

Contents?: true

Size: 1.29 KB

Versions: 2

Compression:

Stored size: 1.29 KB

Contents

# frozen_string_literal: true

module GenAI
  module Api
    module Format
      module Gemini
        USER_ROLE = 'user'
        ASSISTANT_ROLE = 'model'

        def format_messages(messages)
          messages.map { |message| transform_message(message.deep_symbolize_keys) }
        end

        def transform_message(message)
          if message.keys == %i[role content]
            { role: role_for(message), parts: [text: message[:content]] }
          else
            message
          end
        end

        def extract_completions(response)
          if response.is_a?(Array)
            response.map { |completion| extract_candidates(completion) }
          else
            extract_candidates(response)
          end
        end

        def chunk_params_from_streaming(chunk)
          {
            model: 'gemini-pro',
            index: chunk.dig('candidates', 0, 'index'),
            value: chunk.dig('candidates', 0, 'content', 'parts', 0, 'text'),
            raw: chunk
          }
        end

        private

        def extract_candidates(candidates)
          candidates['candidates'].map { |candidate| candidate.dig('content', 'parts', 0, 'text') }
        end

        def role_for(message)
          message[:role] == 'user' ? USER_ROLE : ASSISTANT_ROLE
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
gen-ai-0.4.3 lib/gen_ai/api/format/gemini.rb
gen-ai-0.4.2 lib/gen_ai/api/format/gemini.rb