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
|
# File 'lib/phronomy/agent/context_parts/unit_builders/dependency_aware_unit_builder.rb', line 10
def build(candidates)
ordered = Array(candidates).sort_by do |candidate|
[candidate.sequence || 0, candidate.candidate_id]
end
canonical_assistants = ordered.select do |candidate|
candidate.category == :assistant_message
end
canonical_tool_messages = ordered.select do |candidate|
candidate.category == :tool_message
end.group_by(&:tool_call_id)
assistant_by_tool_call_id = canonical_assistants.each_with_object({}) do |candidate, result|
canonical_tool_call_ids(candidate).each do |tool_call_id|
if result.key?(tool_call_id)
raise ArgumentError,
"duplicate assistant Tool Call id in Context candidates: #{tool_call_id}"
end
result[tool_call_id] = candidate
end
end
claimed = Set.new
units = []
ordered.each do |candidate|
next if claimed.include?(candidate.candidate_id)
group = canonical_tool_exchange(
candidate,
assistant_by_tool_call_id: assistant_by_tool_call_id,
tool_messages: canonical_tool_messages
)
if group && !group.empty?
group.each { |item| claimed << item.candidate_id }
units << build_unit(group, kind: :tool_exchange)
else
claimed << candidate.candidate_id
units << build_unit([candidate], kind: :message)
end
end
units.sort_by { |unit| unit.sequence_range.first }.freeze
end
|