-
-
Notifications
You must be signed in to change notification settings - Fork 439
Expand file tree
/
Copy pathcontent.rb
More file actions
92 lines (74 loc) · 1.92 KB
/
content.rb
File metadata and controls
92 lines (74 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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
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
# frozen_string_literal: true
module RubyLLM
# Represents the content sent to or received from an LLM.
class Content
attr_reader :text, :attachments
def initialize(text = nil, attachments = nil)
@text = text
@attachments = []
process_attachments(attachments)
raise ArgumentError, 'Text and attachments cannot be both nil' if @text.nil? && @attachments.empty?
end
def add_attachment(source, filename: nil)
@attachments << Attachment.new(source, filename:)
self
end
def format
if @text && @attachments.empty?
@text
else
self
end
end
# For Rails serialization
def to_h
{ text: @text, attachments: @attachments.map(&:to_h) }
end
private
def process_attachments_array_or_string(attachments)
Utils.to_safe_array(attachments).each do |file|
next if blank_attachment_entry?(file)
add_attachment(file)
end
end
def blank_attachment_entry?(file)
file.nil? || (file.is_a?(String) && file.strip.empty?)
end
def process_attachments(attachments)
if attachments.is_a?(Hash)
attachments.each_value { |attachment| process_attachments_array_or_string(attachment) }
else
process_attachments_array_or_string attachments
end
end
end
class Content
# Represents provider-specific payloads that should bypass RubyLLM formatting.
class Raw
attr_reader :value
def initialize(value)
raise ArgumentError, 'Raw content payload cannot be nil' if value.nil?
@value = value
end
def format
@value
end
def to_h
@value
end
def to_s
case @value
when String
@value
when Hash, Array
@value.to_json
else
@value.to_s
end
end
def to_json(*args)
@value.to_json(*args)
end
end
end
end