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
|
# File 'lib/legion/extensions/llm/ledger/runners/tools.rb', line 17
def write_tool_record(payload = nil, metadata = {}, **message)
payload, metadata = normalize_runner_args(payload, metadata, message)
= Helpers::SubscriptionMessage.(payload, metadata)
props = metadata[:properties] || {}
body = payload.is_a?(Hash) ? payload : Helpers::Decryption.decrypt_if_needed(payload, metadata)
ctx = body[:message_context] || {}
tool = body[:tool_call] || {}
Helpers::Retention.resolve(
retention: ['x-legion-retention'],
contains_phi: ['x-legion-contains-phi'] == 'true'
)
db = ::Legion::Data.connection
write_result = [:ok]
db.transaction do
response = find_or_resolve_response(db, body, ctx, props, )
identity_attrs = (body, , db)
tool_call_row, new_tool_call = find_or_create_tool_call(db, response, body, ctx, tool, , identity_attrs)
if tool_call_row && !new_tool_call
write_result[0] = :duplicate
elsif new_tool_call
find_or_create_tool_call_attempt(db, tool_call_row, tool, body, props, , identity_attrs)
end
end
{ result: write_result[0] }
rescue Sequel::UniqueConstraintViolation => e
log.warn("write_tool_record duplicate insert ignored: #{e.message}")
{ result: :duplicate }
rescue Helpers::DecryptionUnavailable => e
handle_exception(e, level: :warn, handled: true, operation: 'write_tool_record.decrypt')
raise
rescue Helpers::DecryptionFailed => e
handle_exception(e, level: :error, handled: true, operation: 'write_tool_record.decrypt')
raise
rescue StandardError => e
handle_exception(e, level: :error, handled: true, operation: 'write_tool_record')
{ result: :error, error: e.message }
end
|