Class: Brute::Middleware::ToolPipeline

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

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of ToolPipeline.



12
13
14
15
# File 'lib/brute/middleware/070_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
# File 'lib/brute/middleware/070_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[:events] << on_tool_call_start_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): before_tool may rewrite
          # :arguments or short-circuit with a :result; approve_tool
          # denies on a false (or String) return; after_tool may
          # rewrite :result.
          call_env = {
            name:      name.to_s,
            arguments: args,
            result:    nil,
            events:    env[:events],
            metadata:  {},
            turn_env:  env,
          }
          if (hooks = env[:hooks])
            responses = hooks.emit(:before_tool, call_env).compact
            call_env[:result] = responses.last if call_env[:result].nil? && !responses.empty?

            if call_env[:result].nil?
              denial = hooks.emit(:approve_tool, call_env).find { |r| r == false || r.is_a?(String) }
              unless denial.nil?
                call_env[:result] = denial.is_a?(String) ? denial : %(Tool call to "#{name}" was denied.)
              end
            end
          end

          result = if call_env[:result].nil?
                     available_tools[name].call(call_env[:arguments])
                   else
                     call_env[:result]
                   end

          if (hooks = env[:hooks])
            call_env[:result] = result
            hooks.emit(:after_tool, call_env)
            result = call_env[:result]
          end

          # 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]
        rescue => e
          # 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[:events] << { type: :error, data: { error: e, message: e.message } }
          results << [tool_call, "Error: #{e.class}: #{e.message}"]
        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[:events] << { type: :tool_result, data: { name: tool_call.name, content: content } }
      env[:messages] << Brute::Message.new(role: :tool, content: content, tool_call_id: tool_call.id)
    end
  end

  env
end