Class: Events::Subscribers::LLMResponseHandler

Inherits:
Object
  • Object
show all
Includes:
Events::Subscriber
Defined in:
lib/events/subscribers/llm_response_handler.rb

Overview

Handles the aftermath of a single LLM round-trip emitted via LLMResponded. Persists the assistant’s output as Message records, transitions the session state, and — when the response includes a tool_use block — queues ToolExecutionJob for each tool.

This is where session state moves away from :awaiting: either Session#response_complete! on a text-only response, or Session#tool_received! before dispatching tool work. The drain job itself never transitions state past :awaiting — that is this subscriber’s responsibility, per the SOLID rule that event emission is the final act of a piece.

Instance Method Summary collapse

Instance Method Details

#emit(event) ⇒ Object

Parameters:

  • event (Hash)

    Rails.event notification hash



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/events/subscribers/llm_response_handler.rb', line 23

def emit(event)
  payload = event[:payload]
  session = Session.find(payload[:session_id])

  response = payload[:response] || {}
  api_metrics = payload[:api_metrics]

  log_raw_response(session, response)
  response = Aoide::PhantomCallFilter.call(response)

  tool_uses = normalize_tool_uses(response)
  text = extract_text(response)

  persist_agent_message(session, text, api_metrics) if text.present?
  tool_uses.each { |tool_use| persist_tool_call(session, tool_use) }

  if tool_uses.any?
    session.tool_received! if session.may_tool_received?
    dispatch_tool_executions(session, tool_uses)
  elsif session.may_response_complete?
    session.response_complete!
  end
end