Module: Intelligence::Google::ChatMethods

Included in:
Adapter
Defined in:
lib/intelligence/adapters/google/chat_methods.rb

Constant Summary collapse

GENERATIVE_LANGUAGE_URI =
"https://generativelanguage.googleapis.com/v1beta/models/"
SUPPORTED_BINARY_MEDIA_TYPES =
%w[ text ]
SUPPORTED_BINARY_CONTENT_TYPES =
%w[
  image/png image/jpeg image/webp image/heic image/heif 
  audio/aac audio/flac audio/mp3 audio/m4a audio/mpeg audio/mpga audio/mp4 audio/opus 
  audio/pcm audio/wav audio/webm
  application/pdf 
]
SUPPORTED_FILE_MEDIA_TYPES =
%w[ text ]
SUPPORTED_CONTENT_TYPES =
%w[
  image/png image/jpeg image/webp image/heic image/heif 
  video/x-flv video/quicktime video/mpeg video/mpegps video/mpg video/mp4 video/webm 
  video/wmv video/3gpp
  audio/aac audio/flac audio/mp3 audio/m4a audio/mpeg audio/mpga audio/mp4 audio/opus 
  audio/pcm audio/wav audio/webm
  application/pdf 
]

Instance Method Summary collapse

Instance Method Details

#chat_request_body(conversation, options = {}) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/intelligence/adapters/google/chat_methods.rb', line 58

def chat_request_body( conversation, options = {} )
  options = options ? self.class.configure( options ) : {}
  options = @options.merge( options )

  gc = options[ :generationConfig ]
  # discard properties not part of the google generationConfig schema
  gc.delete( :model )
  gc.delete( :stream )

  result = {}
  result[ :generationConfig ] = gc

  # construct the system prompt in the form of the google schema
  system_instructions = translate_system_message( conversation[ :system_message ] )
  result[ :systemInstruction ] = system_instructions if system_instructions

  result[ :contents ] = []
  conversation[ :messages ]&.each do | message |

    result_message = { role: message[ :role ] == :user ? 'user' : 'model' }
    result_message_parts = []
    
    message[ :contents ]&.each do | content |
      case content[ :type ]
      when :text
        result_message_parts << { text: content[ :text ] }
      when :binary
        content_type = content[ :content_type ]
        bytes = content[ :bytes ]
        if content_type && bytes
          mime_type = MIME::Types[ content_type ].first
          if SUPPORTED_BINARY_MEDIA_TYPES.include?( mime_type&.media_type ) || 
             SUPPORTED_BINARY_CONTENT_TYPES.include?( content_type )
            result_message_parts << {
              inline_data: {
                mime_type: content_type,
                data: Base64.strict_encode64( bytes )
              }
            }
          else
            raise UnsupportedContentError.new( 
              :google, 
              "does not support #{content_type} content type"
            ) 
          end
        else 
          raise UnsupportedContentError.new(
            :google, 
            'requires binary content to include content type and ( packed ) bytes'  
          )
        end 
      when :file
        content_type = content[ :content_type ]
        uri = content[ :uri ]
        if content_type && uri
          mime_type = MIME::Types[ content_type ].first
          if SUPPORTED_FILE_MEDIA_TYPES.include?( mime_type&.media_type ) || 
             SUPPORTED_FILE_CONTENT_TYPES.include?( content_type )
            result_message_parts << {
              file_data: {
                mime_type: content_type,
                file_uri: uri
              }
            }
          else
            raise UnsupportedContentError.new( 
              :google, 
              "does not support #{content_type} content type"
            ) 
          end
        else 
          raise UnsupportedContentError.new(
            :google, 
            'requires file content to include content type and uri'  
          )
        end 
 
      else 
        raise InvalidContentError.new( :google ) 
      end 
    end

    result_message[ :parts ] = result_message_parts
    result[ :contents ] << result_message

  end

  JSON.generate( result )

end

#chat_request_headers(options = {}) ⇒ Object



54
55
56
# File 'lib/intelligence/adapters/google/chat_methods.rb', line 54

def chat_request_headers( options = {} )
  { 'Content-Type' => 'application/json' }
end

#chat_request_uri(options) ⇒ Object

Raises:

  • (ArgumentError)


29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/intelligence/adapters/google/chat_methods.rb', line 29

def chat_request_uri( options )
  options = options ? self.class.configure( options ) : {}
  options = @options.merge( options )

  key = options[ :key ] 
  gc = options[ :generationConfig ] || {}
  model = gc[ :model ]
  stream = gc.key?( :stream ) ? gc[ :stream ] : false 

  raise ArgumentError.new( "A Google API key is required to build a Google chat request." ) \
    if key.nil?
  raise ArgumentError.new( "A Google model is required to build a Google chat request." ) \
    if model.nil?
  
  uri = URI( GENERATIVE_LANGUAGE_URI )
  path = File.join( uri.path, model )
  path += stream ? ':streamGenerateContent' : ':generateContent'
  uri.path = path
  query = { key: key }
  query[ :alt ] = 'sse' if stream
  uri.query = URI.encode_www_form( query )

  uri.to_s
end

#chat_result_attributes(response) ⇒ Object



149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
# File 'lib/intelligence/adapters/google/chat_methods.rb', line 149

def chat_result_attributes( response )

  return nil unless response.success?

  response_json = JSON.parse( response.body, symbolize_names: true ) rescue nil
  return nil \
    if response_json.nil? || response_json[ :candidates ].nil?
  
  result = {}
  result[ :choices ] = []

  response_json[ :candidates ]&.each do | response_choice |

    end_reason = translate_finish_reason( response_choice[ :finishReason ] )
    
    role = nil 
    contents = []

    response_content = response_choice[ :content ]
    if response_content
      role = ( response_content[ :role ] == 'model' ) ? 'assistant' : 'user'

      contents = []
      response_content[ :parts ]&.each do | response_content_part |
        if response_content_part.key?( :text )              
          contents.push( {
            type: 'text', text: response_content_part[ :text ]
          } )
        end
      end
    end

    result_message = nil 
    if role
      result_message = { role: role }
      result_message[ :contents ] = contents
    end

    result[ :choices ].push( { end_reason: end_reason, message: result_message } )
  
  end

  metrics_json = response_json[ :usageMetadata ]
  unless metrics_json.nil?

    metrics = {}
    metrics[ :input_tokens ] = metrics_json[ :promptTokenCount ] 
    metrics[ :output_tokens ] = metrics_json[ :candidatesTokenCount ]
    metrics = metrics.compact

    result[ :metrics ] = metrics unless metrics.empty?

  end

  result

end

#chat_result_error_attributes(response) ⇒ Object Also known as: stream_result_error_attributes



207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
# File 'lib/intelligence/adapters/google/chat_methods.rb', line 207

def chat_result_error_attributes( response )

  error_type, error_description = translate_error_response_status( response.status )
  result = { error_type: error_type.to_s, error_description: error_description }

  response_body = JSON.parse( response.body, symbolize_names: true ) rescue nil 
  if response_body && response_body[ :error ]
    error_details_reason = response_body[ :error ][ :details ]&.first&.[]( :reason )
    # a special case for authentication 
    error_type = :authentication_error if error_details_reason == 'API_KEY_INVALID'
    result = {
      error_type: error_type.to_s,
      error: error_details_reason || response_body[ :error ][ :status ] || error_type,
      error_description: response_body[ :error ][ :message ]
    }
  end
  result

end

#stream_result_attributes(context) ⇒ Object



306
307
308
309
310
311
312
313
314
315
316
317
318
# File 'lib/intelligence/adapters/google/chat_methods.rb', line 306

def stream_result_attributes( context )
#--------------------------------------

  choices = context[ :choices ]
  metrics = context[ :metrics ]

  choices = choices.map do | choice |
    { end_reason: choice[ :end_reason ] }
  end

  { choices: choices, metrics: context[ :metrics ] }

end

#stream_result_chunk_attributes(context, chunk) ⇒ Object



227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
# File 'lib/intelligence/adapters/google/chat_methods.rb', line 227

def stream_result_chunk_attributes( context, chunk )
#---------------------------------------------------

  context ||= {}
  buffer = context[ :buffer ] || ''
  metrics = context[ :metrics ] || {
    input_tokens: 0,
    output_tokens:  0
  }
  choices = context[ :choices ] || Array.new( 1 , { message: {} } )

  choices.each do | choice |
    choice[ :message ][ :contents ] = choice[ :message ][ :contents ]&.map do | content |
      case content[ :type ] 
        when :text 
          content[ :text ] = ''
        else 
          content.clear 
      end
      content
    end
  end

  buffer += chunk
  while ( eol_index = buffer.index( "\n" ) )

    line = buffer.slice!( 0..eol_index )        
    line = line.strip 
    next if line.empty? || !line.start_with?( 'data:' )
    line = line[ 6..-1 ]

    data = JSON.parse( line, symbolize_names: true )
    if data.is_a?( Hash )
      
      data[ :candidates ]&.each do | data_candidate |

        data_candidate_index = data_candidate[ :index ] || 0
        data_candidate_content = data_candidate[ :content ]
        data_candidate_finish_reason = data_candidate[ :finishReason ]
        choices.fill( { message: { role: 'assistant' } }, choices.size, data_candidate_index + 1 ) \
          if choices.size <= data_candidate_index 
        contents = choices[ data_candidate_index ][ :message ][ :contents ] || []
        last_content = contents&.last 
        
        if data_candidate_content&.include?( :parts ) 
          data_candidate_content_parts = data_candidate_content[ :parts ]
          data_candidate_content_parts&.each do | data_candidate_content_part |
            if data_candidate_content_part.key?( :text )
              if last_content.nil? || last_content[ :type ] != :text
                contents.push( { type: :text, text: data_candidate_content_part[ :text ] } )
              else 
                last_content[ :text ] = 
                  ( last_content[ :text ] || '' ) + data_candidate_content_part[ :text ]
              end
            end
          end
        end
        choices[ data_candidate_index ][ :message ][ :contents ] = contents
        choices[ data_candidate_index ][ :end_reason ] = 
          translate_finish_reason( data_candidate_finish_reason )
      end
  
      if usage = data[ :usageMetadata ]
        metrics[ :input_tokens ] = usage[ :promptTokenCount ]
        metrics[ :output_tokens ] = usage[ :candidatesTokenCount ]
      end 

    end

  end

  context[ :buffer ] = buffer 
  context[ :metrics ] = metrics
  context[ :choices ] = choices

  [ context, choices.empty? ? nil : { choices: choices.dup } ]

end