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>)


47
48
49
50
51
# File 'lib/omniai/anthropic/chat/message_serializer.rb', line 47

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)


30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/omniai/anthropic/chat/message_serializer.rb', line 30

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

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

  tool_call_list = OmniAI::Chat::ToolCallList.new(entries: tool_call_parts) if tool_call_parts.any?
  content = non_tool_call_parts if non_tool_call_parts.any?

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

.serialize(message, context:) ⇒ Hash

Parameters:

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

Returns:

  • (Hash)


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

def self.serialize(message, context:)
  role = message.role
  parts = arrayify(message.content) + arrayify(message.tool_call_list&.entries)

  content = parts.map do |part|
    case part
    when String then { type: "text", text: part }
    else part.serialize(context:)
    end
  end

  { role:, content: }
end