Class: ActiveAgent::Providers::Common::Messages::Assistant

Inherits:
Base
  • Object
show all
Defined in:
lib/active_agent/providers/common/messages/assistant.rb

Overview

Represents messages sent by the AI assistant in a conversation.

Instance Method Summary collapse

Methods inherited from BaseModel

#<=>, #==, attribute, #deep_compact, #deep_dup, delegate_attributes, drop_attributes, inherited, #initialize, #inspect, keys, #merge!, required_attributes, #serialize, #to_h, #to_hash

Constructor Details

This class inherits a constructor from ActiveAgent::Providers::Common::BaseModel

Instance Method Details

#parsed_json(symbolize_names: true, normalize_names: :underscore) ⇒ Hash, ... Also known as: json_object, parse_json

Extracts and parses JSON object or array from message content.

Searches for the first occurrence of ‘or `[` and last occurrence of `` or `]`, then parses the content between them. Useful for extracting structured data from assistant messages that may contain additional text around the JSON.



26
27
28
29
30
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
# File 'lib/active_agent/providers/common/messages/assistant.rb', line 26

def parsed_json(symbolize_names: true, normalize_names: :underscore)
  # Handle array content (from content blocks) by searching through each block
  content_str = if content.is_a?(Array)
    content.map { |block| block.is_a?(Hash) ? block[:text] : block.to_s }.join("\n")
  else
    content.to_s
  end

  start_char       = [ content_str.index("{"),  content_str.index("[") ].compact.min
  end_char         = [ content_str.rindex("}"), content_str.rindex("]") ].compact.max
  content_stripped = content_str[start_char..end_char] if start_char && end_char
  return unless content_stripped

  content_parsed = JSON.parse(content_stripped)

  transform_hash = ->(hash) do
    next if hash.nil?

    hash = hash.deep_transform_keys(&normalize_names) if normalize_names
    hash = hash.deep_symbolize_keys if symbolize_names
    hash
  end

  case content_parsed
  when Hash  then transform_hash.call(content_parsed)
  when Array then content_parsed.map { |item| item.is_a?(Hash) ? transform_hash.call(item) : item }
  else content_parsed
  end
rescue JSON::ParserError
  nil
end

#textObject

Returns content as a string, handling both string and array formats



59
60
61
62
63
64
65
# File 'lib/active_agent/providers/common/messages/assistant.rb', line 59

def text
  if content.is_a?(Array)
    content.map { |block| block.is_a?(Hash) ? block[:text] : block.to_s }.join("\n")
  else
    content.to_s
  end
end