Class: Brute::Middleware::DefaultToolPipeline

Inherits:
Base
  • Object
show all
Defined in:
lib/brute/middleware/070_default_tool_pipeline.rb

Constant Summary

Constants included from Hooks

Hooks::COMPACT_DURATION_EVENT, Hooks::COMPACT_END_EVENT, Hooks::COMPACT_FAILURE_EVENT, Hooks::COMPACT_START_EVENT, Hooks::CONTENT_EVENT, Hooks::FARADAY_ERROR_EVENT, Hooks::LLM_DURATION_EVENT, Hooks::LLM_END_EVENT, Hooks::LLM_FAILURE_EVENT, Hooks::LLM_START_EVENT, Hooks::MIDDLEWARE_ADDED_EVENT, Hooks::MIDDLEWARE_DURATION_EVENT, Hooks::MIDDLEWARE_END_EVENT, Hooks::MIDDLEWARE_FAILURE_EVENT, Hooks::MIDDLEWARE_START_EVENT, Hooks::OPEN_ROUTER_SERVER_ERROR_EVENT, Hooks::REASONING_EVENT, Hooks::STANDARD_ERROR_EVENT, Hooks::TOOL_APPROVE_EVENT, Hooks::TOOL_CALLS_EVENT, Hooks::TOOL_DURATION_EVENT, Hooks::TOOL_END_EVENT, Hooks::TOOL_FAILURE_EVENT, Hooks::TOOL_START_EVENT, Hooks::TURN_DURATION_EVENT, Hooks::TURN_END_EVENT, Hooks::TURN_FAILURE_EVENT, Hooks::TURN_START_EVENT

Instance Method Summary collapse

Constructor Details

#initialize(app, tools: []) ⇒ DefaultToolPipeline

Returns a new instance of DefaultToolPipeline.



12
13
14
15
# File 'lib/brute/middleware/070_default_tool_pipeline.rb', line 12

def initialize(app, tools: [])
  @app   = app
  @tools = tools
end

Instance Method Details

#call(env) ⇒ Object



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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/brute/middleware/070_default_tool_pipeline.rb', line 17

def call(env)
  env[:tools] = @tools
  @app.call(env)

  response = env[:messages].last

  if response.respond_to?(:tool_calls) && response.tool_calls.present?
    tools_to_run = response.tool_calls

    # tool_to_run may be an Array (Brute::ToolCall) or an id-keyed Hash (some libraries' native shape)
    if tools_to_run.respond_to?(:values)
      tools_to_run = tools_to_run.values
    end

    # No idea why we use Array() here... probably in case it's a hash or something...
    # because reject would work on the hash...
    tools_to_run = Array(tools_to_run).reject { |tc| tc.name == "question" }

    available_tools = Brute::Tools::Adapter.wrap_all(env[:tools])
    env.emit(TOOL_CALLS_EVENT, tools_to_run)

    results = []

    # Async::Barrier blocks until all tasks are complete.
    # Tasks run in parrallel.
    #
    Sync do
      barrier = Async::Barrier.new

      tools_to_run.each do |tool_call|
        barrier.async do
          name = tool_call.name.to_sym
          args = tool_call.arguments

          # Lifecycle hooks (Brute::Hooks): tool_start may rewrite
          # :arguments or short-circuit with a :result; tool_approve
          # denies on a false (or String) return; tool_end may
          # rewrite :result.
          call_env = {
            name:      name.to_s,
            arguments: args,
            result:    nil,
            denied:    nil,
            metadata:  {},
            turn_env:  env,
          }
          env.emit_trace do |env|
            # A subscriber takes part by mutating the call env: set
            # :result to answer without executing, set :denied to refuse.
            env.emit(TOOL_START_EVENT, call_env)

            if call_env[:result].nil?
              env.emit(TOOL_APPROVE_EVENT, call_env)

              if (denial = call_env[:denied])
                if denial.is_a?(String)
                  call_env[:result] = denial
                else
                  call_env[:result] = %(Tool call to "#{name}" was denied.)
                end
              end
            end

            # Only the tool's own execution is timed: a call that
            # tool_start answered, or tool_approve denied, never ran.
            result = call_env[:result]

            if result.nil?
              env.emit(TOOL_DURATION_EVENT, call_env) do
                result = available_tools[name].call(call_env[:arguments])
              end
            end

            call_env[:result] = result
            env.emit(TOOL_END_EVENT, call_env)
          rescue => error
            # Capture the error as a tool result so the LLM can see it
            # and reason about the failure, rather than crashing the
            # entire middleware chain.
            env.emit(TOOL_FAILURE_EVENT, call_env, error)
            call_env[:result] = "Error: #{error.class}: #{error.message}"
          end
          result = call_env[:result]

          # Coerce to String so Hash results (e.g. Shell's
          # {stdout:, stderr:, exit_code:}) serialize predictably.
          if result.is_a?(String)
            content = result
          else
            content = result.to_s
          end

          # Universal truncation safety net — skip if already truncated
          unless Brute::Truncation.already_truncated?(content)
            content = Brute::Truncation.truncate(content)
          end

          results << [tool_call, content]
        end
      end

      barrier.wait
    ensure
      barrier&.cancel
    end

    # Append events and messages in the original tool_call order so the
    # LLM sees a deterministic sequence regardless of completion order.
    results.sort_by! { |tool_call, _| tools_to_run.index(tool_call) }

    results.each do |tool_call, content|
      env[:messages] << Brute::Message.new(role: :tool, content: content, tool_call_id: tool_call.id)
    end
  end

  env
end