Module: Intelligence::Anthropic::ChatRequestMethods

Defined in:
lib/intelligence/adapters/anthropic/chat_request_methods.rb

Constant Summary collapse

CHAT_REQUEST_URI =
"https://api.anthropic.com/v1/messages"
SUPPORTED_CONTENT_TYPES =
%w[ image/jpeg image/png image/gif image/webp application/pdf ]

Instance Method Summary collapse

Instance Method Details

#chat_request_body(conversation, options = nil) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/intelligence/adapters/anthropic/chat_request_methods.rb', line 31

def chat_request_body( conversation, options = nil )
  tools = options.delete( :tools ) || []

  options = merge_options( @options, build_options( options ) )
  result = options[ :chat_options ]&.compact || {}

  system_message = to_anthropic_system_message( conversation[ :system_message ] )
  result[ :system ] = system_message unless system_message.nil?
  result[ :messages ] = []

  messages = conversation[ :messages ] 
  length = messages&.length || 0
  index = 0; while index < length 
    
    message = messages[ index ]
    unless message.nil?

      # The Anthropic API will not accept a sequence of messages where the role of two 
      # sequentian messages is the same.
      #
      # The purpose of this code is to identify such occurences and coalece them such 
      # that the first message in the sequence aggregates the contents of all subsequent
      # messages with the same role.
      look_ahead_index = index + 1; while look_ahead_index < length
        ahead_message = messages[ look_ahead_index ]
        unless ahead_message.nil?
          if ahead_message[ :role ] == message[ :role ]
            message[ :contents ] = 
              ( message[ :contents ] || [] ) + 
              ( ahead_message[ :contents ] || [] )
            messages[ look_ahead_index ] = nil 
            look_ahead_index += 1
          else 
            break
          end
        end
      end

      result_message = { role: message[ :role ] }
      result_message_content = []
      
      message[ :contents ]&.each do | content |
        case content[ :type ]
        when :text
          result_message_content << { type: 'text', text: content[ :text ] }
        when :binary
          content_type = content[ :content_type ]
          bytes = content[ :bytes ]
          if content_type && bytes
            if SUPPORTED_CONTENT_TYPES.include?( content_type )
              result_message_content << {
                type: content_type == 'application/pdf' ? 'document' : 'image',
                source: {
                  type: 'base64',
                  media_type: content_type,
                  data: Base64.strict_encode64( bytes )
                }
              }
            else
              raise UnsupportedContentError.new( 
                :anthropic, 
                'only support content of type image/*' 
              ) 
            end
          else 
            raise UnsupportedContentError.new(
              :anthropic, 
              'requires file content to include content type and (packed) bytes'  
            )
          end
        when :file 
          content_type = content[ :content_type ]
          uri = content[ :uri ]
          if content_type && uri  
            if SUPPORTED_CONTENT_TYPES.include?( content_type )
              result_message_content << {
                type: content_type == 'application/pdf' ? 'document' : 'image',
                source: {
                  type: 'url',
                  url: uri 
                }
              }
            else 
              raise UnsupportedContentError.new( 
                :anthropic, 
                "only supports content of type #{SUPPORTED_CONTENT_TYPES.join( ', ' )}" 
              ) 
            end 
          else 
            raise UnsupportedContentError.new(
              :anthropic, 
              'requires file content to include content type and uri'  
            )
          end 
        when :tool_call 
          result_message_content << {
            type: 'tool_use',
            id: content[ :tool_call_id ],
            name: content[ :tool_name ],
            input: content[ :tool_parameters ] || {}
          }
        when :tool_result 
          result_message_content << {
            type: 'tool_result',
            tool_use_id: content[ :tool_call_id ],
            content: content[ :tool_result ]
          }
        else
          raise UnsupportedContentError.new( :anthropic ) 
        end
      end
      
      result_message[ :content ] = result_message_content
      result[ :messages ] << result_message
    
    end
  
    index += 1 

  end
  
  tools_attributes = chat_request_tools_attributes( 
    ( result[ :tools ] || [] ).concat( tools ) 
  )
  result[ :tools ] = tools_attributes if tools_attributes && tools_attributes.length > 0

  JSON.generate( result )
end

#chat_request_headers(options = nil) ⇒ Object

Raises:

  • (ArgumentError)


13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/intelligence/adapters/anthropic/chat_request_methods.rb', line 13

def chat_request_headers( options = nil )
  options = merge_options( @options, build_options( options ) )
  result = {}

  key = options[ :key ] 
  version = options[ :version ] || "2023-06-01" 

  raise ArgumentError.new( 
    "An Anthropic key is required to build an Anthropic chat request." 
  ) if key.nil?

  result[ 'content-type' ] = 'application/json'
  result[ 'x-api-key' ] = "#{key}"
  result[ 'anthropic-version' ] = version unless version.nil?

  result 
end

#chat_request_tools_attributes(tools) ⇒ Object



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
# File 'lib/intelligence/adapters/anthropic/chat_request_methods.rb', line 160

def chat_request_tools_attributes( tools ) 
  properties_array_to_object = lambda do | properties |
    return nil unless properties&.any?  
    object = {}
    required = []
    properties.each do | property | 
      name = property.delete( :name ) 
      required << name if property.delete( :required )
      if property[ :properties ]&.any?  
        property_properties, property_required = 
          properties_array_to_object.call( property[ :properties ] ) 
        property[ :properties ] = property_properties 
        property[ :required ] = property_required if property_required.any?
      end 
      object[ name ] = property 
    end 
    [ object, required.compact  ]
  end

  tools&.map do | tool |
    tool_attributes = { 
      name: tool[ :name ],
      description: tool[ :description ],
      input_schema: { type: 'object' }
    }

    if tool[ :properties ]&.any? 
      properties_object, properties_required = 
        properties_array_to_object.call( tool[ :properties ] ) 
      input_schema = {
        type: 'object',
        properties: properties_object 
      }
      input_schema[ :required ] = properties_required if properties_required.any?
      tool_attributes[ :input_schema ] = input_schema
    end
    tool_attributes 
  end
end

#chat_request_uri(options) ⇒ Object



9
10
11
# File 'lib/intelligence/adapters/anthropic/chat_request_methods.rb', line 9

def chat_request_uri( options )
  CHAT_REQUEST_URI
end