Module: Legion::LLM::Inference::AuditPublisher

Extended by:
Legion::Logging::Helper
Defined in:
lib/legion/llm/inference/audit_publisher.rb

Class Method Summary collapse

Class Method Details

.build_event(request:, response:) ⇒ Object



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
# File 'lib/legion/llm/inference/audit_publisher.rb', line 12

def build_event(request:, response:)
  log.debug("[audit_publisher][build_event] action=build request_id=#{response.request_id} conversation_id=#{response.conversation_id}")

  resp_message = response.message
  msg_content = resp_message.is_a?(Types::Message) ? resp_message.text : resp_message[:content]
  msg_id = resp_message.is_a?(Types::Message) ? resp_message.id : nil
  msg_task_id = resp_message.is_a?(Types::Message) ? resp_message.task_id : nil
  msg_conversation_id = resp_message.is_a?(Types::Message) ? resp_message.conversation_id : nil

  tools_data = Array(response.tools).map do |tc|
    tc.is_a?(Types::ToolCall) ? tc.to_audit_hash : tc
  end

  event = {
    request_id:       response.request_id,
    conversation_id:  response.conversation_id,
    caller:           response.caller,
    routing:          response.routing,
    tokens:           response.tokens,
    cost:             response.cost,
    enrichments:      response.enrichments,
    audit:            response.audit,
    timeline:         response.timeline,
    timestamps:       response.timestamps,
    classification:   response.classification,
    tracing:          response.tracing,
    messages:         request.messages,
    response_content: msg_content,
    tools_used:       tools_data,
    timestamp:        Time.now,
    request_type:     request.respond_to?(:request_type) ? request.request_type : 'chat',
    tier:             response.routing.is_a?(Hash) ? response.routing[:tier] : nil,
    message_context:  build_message_context(request: request, response: response)
  }
  event[:message_id] = msg_id if msg_id
  event[:task_id] = msg_task_id if msg_task_id
  event[:message_conversation_id] = msg_conversation_id if msg_conversation_id
  event
end

.build_message_context(response:) ⇒ Object



61
62
63
64
65
66
# File 'lib/legion/llm/inference/audit_publisher.rb', line 61

def build_message_context(response:, **)
  {
    request_id:      response.request_id,
    conversation_id: response.conversation_id
  }.compact
end

.publish(request:, response:) ⇒ Object



52
53
54
55
56
57
58
59
# File 'lib/legion/llm/inference/audit_publisher.rb', line 52

def publish(request:, response:)
  event = build_event(request: request, response: response)
  Legion::LLM::Audit.emit_prompt(event)
  event
rescue StandardError => e
  handle_exception(e, level: :warn)
  nil
end