Module: Raif::Messages

Defined in:
lib/raif/messages.rb

Overview

Message types for agent conversation_history and conversation llm_messages.

These classes provide a structured API for creating messages that get stored as JSONB and passed to LLM providers. Each class has:

  • Named parameters for initialization

  • ‘to_h` for converting to hash format (for storage/API calls)

  • ‘from_h` class method for deserializing from stored hashes

Examples:

Creating messages

message = Raif::Messages::ToolCall.new(
  name: "wikipedia_search",
  arguments: { query: "Ruby" },
  provider_tool_call_id: "call_123"
)
conversation_history << message.to_h

Deserializing stored messages

messages = Raif::Messages.from_array(agent.conversation_history)
messages.each do |msg|
  case msg
  when Raif::Messages::ToolCall
    puts "Tool: #{msg.name}"
  when Raif::Messages::UserMessage
    puts "User: #{msg.content}"
  end
end

Defined Under Namespace

Classes: AssistantMessage, ToolCall, ToolCallResult, UserMessage

Class Method Summary collapse

Class Method Details

.from_array(messages) ⇒ Array<UserMessage, AssistantMessage, ToolCall, ToolCallResult>

Deserialize an array of message hashes

Parameters:

  • messages (Array<Hash>)

    Array of message hashes

Returns:



175
176
177
# File 'lib/raif/messages.rb', line 175

def from_array(messages)
  messages.map { |msg| from_h(msg) }
end

.from_h(hash) ⇒ UserMessage, ...

Deserialize a single message hash into the appropriate message class

Parameters:

  • hash (Hash)

    A message hash with either “role” or “type” key

Returns:

Raises:

  • (ArgumentError)

    if the hash doesn’t match a known message type



158
159
160
161
162
163
164
165
166
167
168
169
170
# File 'lib/raif/messages.rb', line 158

def from_h(hash)
  if hash["type"] == "tool_call"
    ToolCall.from_h(hash)
  elsif hash["type"] == "tool_call_result"
    ToolCallResult.from_h(hash)
  elsif hash["role"] == "user"
    UserMessage.from_h(hash)
  elsif hash["role"] == "assistant"
    AssistantMessage.from_h(hash)
  else
    raise ArgumentError, "Unknown message type: #{hash.inspect}"
  end
end