Module: OmniAI::Anthropic::Chat::MessageSerializer

Defined in:
lib/omniai/anthropic/chat/message_serializer.rb

Overview

Overrides message serialize / deserialize.

Class Method Summary collapse

Class Method Details

.arrayify(content) ⇒ Array<Object>

Parameters:

  • content (Object)

Returns:

  • (Array<Object>)


41
42
43
44
45
# File 'lib/omniai/anthropic/chat/message_serializer.rb', line 41

def self.arrayify(content)
  return [] if content.nil?

  content.is_a?(Array) ? content : [content]
end

.deserialize(data, context:) ⇒ OmniAI::Chat::Message

Parameters:

  • data (Hash)
  • context (OmniAI::Context)

Returns:

  • (OmniAI::Chat::Message)


27
28
29
30
31
32
33
34
35
36
37
# File 'lib/omniai/anthropic/chat/message_serializer.rb', line 27

def self.deserialize(data, context:)
  role = data['role']
  parts = arrayify(data['content']).map do |content|
    ContentSerializer.deserialize(content, context:)
  end

  tool_call_list = parts.select { |part| part.is_a?(OmniAI::Chat::ToolCall) }
  content = parts.reject { |part| part.is_a?(OmniAI::Chat::ToolCall) }

  OmniAI::Chat::Message.new(content:, role:, tool_call_list:)
end

.serialize(message, context:) ⇒ Hash

Parameters:

  • message (OmniAI::Chat::Message)
  • context (OmniAI::Context)

Returns:

  • (Hash)


11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/omniai/anthropic/chat/message_serializer.rb', line 11

def self.serialize(message, context:)
  role = message.role
  parts = arrayify(message.content) + arrayify(message.tool_call_list)
  content = parts.map do |part|
    case part
    when String then { type: 'text', text: part }
    else part.serialize(context:)
    end
  end

  { role:, content: }
end