Class: Foobara::Agent::AccomplishGoal

Inherits:
Command
  • Object
show all
Defined in:
foobara-agent-0.1.1/src/foobara/agent/accomplish_goal.rb

Constant Summary collapse

RETRY_COUNT =
3

Constants included from TruncatedInspect

TruncatedInspect::MAX_LENGTH

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Command

install!

Methods included from CommandPatternImplementation

install_state_machine_callback_methods

Methods included from TruncatedInspect

#inspect, truncating

Methods included from Concern

foobara_class_methods_module_for, foobara_concern?, included

Instance Attribute Details

#command_calls ⇒ Object

Returns the value of attribute command_calls.



61
62
63
# File 'src/foobara/agent/accomplish_goal.rb', line 61

def command_calls
  @command_calls
end

#command_outcome ⇒ Object

Returns the value of attribute command_outcome.



61
62
63
# File 'src/foobara/agent/accomplish_goal.rb', line 61

def command_outcome
  @command_outcome
end

#command_response ⇒ Object

Returns the value of attribute command_response.



61
62
63
# File 'src/foobara/agent/accomplish_goal.rb', line 61

def command_response
  @command_response
end

#delayed_command_name ⇒ Object

Returns the value of attribute delayed_command_name.



61
62
63
# File 'src/foobara/agent/accomplish_goal.rb', line 61

def delayed_command_name
  @delayed_command_name
end

#final_message ⇒ Object

Returns the value of attribute final_message.



61
62
63
# File 'src/foobara/agent/accomplish_goal.rb', line 61

def final_message
  @final_message
end

#final_result ⇒ Object

Returns the value of attribute final_result.



61
62
63
# File 'src/foobara/agent/accomplish_goal.rb', line 61

def final_result
  @final_result
end

#given_up ⇒ Object

Returns the value of attribute given_up.



61
62
63
# File 'src/foobara/agent/accomplish_goal.rb', line 61

def given_up
  @given_up
end

#killed ⇒ Object

Returns the value of attribute killed.



61
62
63
# File 'src/foobara/agent/accomplish_goal.rb', line 61

def killed
  @killed
end

#llm_call_timestamps ⇒ Object



535
536
537
# File 'src/foobara/agent/accomplish_goal.rb', line 535

def llm_call_timestamps
  @llm_call_timestamps ||= []
end

#mission_accomplished ⇒ Object

Returns the value of attribute mission_accomplished.



61
62
63
# File 'src/foobara/agent/accomplish_goal.rb', line 61

def mission_accomplished
  @mission_accomplished
end

#next_command ⇒ Object

Returns the value of attribute next_command.



61
62
63
# File 'src/foobara/agent/accomplish_goal.rb', line 61

def next_command
  @next_command
end

#next_command_class ⇒ Object

Returns the value of attribute next_command_class.



61
62
63
# File 'src/foobara/agent/accomplish_goal.rb', line 61

def next_command_class
  @next_command_class
end

#next_command_inputs ⇒ Object

Returns the value of attribute next_command_inputs.



61
62
63
# File 'src/foobara/agent/accomplish_goal.rb', line 61

def next_command_inputs
  @next_command_inputs
end

#next_command_name ⇒ Object

Returns the value of attribute next_command_name.



61
62
63
# File 'src/foobara/agent/accomplish_goal.rb', line 61

def next_command_name
  @next_command_name
end

#next_command_raw_inputs ⇒ Object

Returns the value of attribute next_command_raw_inputs.



61
62
63
# File 'src/foobara/agent/accomplish_goal.rb', line 61

def next_command_raw_inputs
  @next_command_raw_inputs
end

#timed_out ⇒ Object

Returns the value of attribute timed_out.



61
62
63
# File 'src/foobara/agent/accomplish_goal.rb', line 61

def timed_out
  @timed_out
end

Instance Method Details

#add_given_up_error ⇒ Object



468
469
470
# File 'src/foobara/agent/accomplish_goal.rb', line 468

def add_given_up_error
  add_runtime_error(:gave_up, reason: final_message)
end

#all_command_classes ⇒ Object



264
265
266
# File 'src/foobara/agent/accomplish_goal.rb', line 264

def all_command_classes
  @all_command_classes ||= run_subcommand!(ListCommands, command_connector: agent).values.flatten
end

#build_result ⇒ Object



485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
# File 'src/foobara/agent/accomplish_goal.rb', line 485

def build_result
  result_data = if final_result_type_from_declaration
                  outcome = final_result_type_from_declaration.process_value(final_result)

                  if outcome.success?
                    outcome.result
                  elsif given_up? || killed?
                    final_result
                  else
                    # simplecov:disable
                    raise CommandPatternImplementation::Concerns::Result::CouldNotProcessResult,
                          outcome.errors
                    # simplecov:enable
                  end
                else
                  final_result
                end

  {
    message_to_user: final_message,
    result_data:
  }
end

#check_if_too_many_calls ⇒ Object



357
358
359
360
361
362
363
364
365
366
# File 'src/foobara/agent/accomplish_goal.rb', line 357

def check_if_too_many_calls
  if command_calls > maximum_command_calls
    add_runtime_error(
      :too_many_command_calls,
      "Too many command calls. " \
      "Stopping. Increase maximum_command_calls if #{maximum_command_calls} is not enough.",
      maximum_command_calls:
    )
  end
end

#command_described?(command_name) ⇒ Boolean

Returns:

  • (Boolean)


531
532
533
# File 'src/foobara/agent/accomplish_goal.rb', line 531

def command_described?(command_name)
  described_commands.include?(command_name)
end

#command_name_type ⇒ Object



260
261
262
# File 'src/foobara/agent/accomplish_goal.rb', line 260

def command_name_type
  @command_name_type ||= Agent.foobara_type_from_declaration(:string, one_of: all_command_classes)
end

#compact_command_log ⇒ Object



291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
# File 'src/foobara/agent/accomplish_goal.rb', line 291

def compact_command_log
  # Rules:
  # Delete errors for any command that has succeeded since
  # Delete all but the last DescribeCommand call for a given
  describe_command_call_indexes = {}
  commands = {}

  describe_command_name = DescribeCommand.full_command_name
  context.command_log.each.with_index do |command_log_entry, index|
    command_name = command_log_entry.command_name

    if command_name == describe_command_name
      described_command = command_log_entry.inputs[:command_name]

      if command_log_entry.outcome[:success]
        describe_command_call_indexes[described_command] ||= []
        describe_command_call_indexes[described_command] << index
      end
    end

    commands[command_name] ||= [[], []]
    bucket_index = command_log_entry.outcome[:success] ? 0 : 1
    commands[command_name][bucket_index] << index
  end

  indexes_to_delete = []

  describe_command_call_indexes.each_value do |indexes|
    indexes_to_delete += indexes[0..-2]
  end

  commands.each_value do |(success_indexes, failure_indexes)|
    last_success = success_indexes.last
    next unless last_success

    failure_indexes.each do |failure_index|
      # TODO: test this path
      # simplecov:disable
      if failure_index < last_success
        indexes_to_delete << failure_index
      else
        break
      end
      # simplecov:enable
    end
  end

  if indexes_to_delete.empty?
    return
  end

  new_log = []
  context.command_log = context.command_log.each.with_index do |entry, index|
    unless indexes_to_delete.include?(index)
      new_log << entry
    end
  end

  context.command_log = new_log
end

#context ⇒ Object



545
546
547
# File 'src/foobara/agent/accomplish_goal.rb', line 545

def context
  agent.context
end

#described_commands ⇒ Object



509
510
511
# File 'src/foobara/agent/accomplish_goal.rb', line 509

def described_commands
  @described_commands ||= Set.new
end

#determine_next_command_and_inputs(retries = RETRY_COUNT, error_outcome = nil) ⇒ Object



129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
# File 'src/foobara/agent/accomplish_goal.rb', line 129

def determine_next_command_and_inputs(retries = RETRY_COUNT, error_outcome = nil)
  return if killed

  if verbose? && retries != RETRY_COUNT
    # simplecov:disable
    (io_err || $stderr).puts " !!! Retrying to determine next command and inputs. Retries left: #{retries}"
    # simplecov:enable
  end

  if retries == 0
    # TODO: test this path by irreparably breaking the needed commands
    # simplecov:disable
    self.next_command_name = GiveUp.full_command_name
    self.next_command_inputs = {
      message_to_user: "While trying to choose the next command and inputs, " \
                       "I've ran into an error several times that I couldn't figure out how to get past. " \
                       "The last error looked like this:\n#{error_outcome.errors_hash}"
    }
    self.next_command_raw_inputs = next_command_inputs

    return
    # simplecov:enable
  end

  compact_command_log

  inputs_for_determine = { agent:, llm_model: }
  unless pass_aggregates_to_llm.nil?
    inputs_for_determine[:pass_aggregates_to_llm] = pass_aggregates_to_llm
  end
  determine_command = DetermineNextCommandNameAndInputs.new(inputs_for_determine)

  outcome = begin
    record_llm_call_timestamp
    determine_command.run
  rescue CommandPatternImplementation::Concerns::Result::CouldNotProcessResult => e
    # simplecov:disable
    Outcome.errors(e.errors)
    # simplecov:enable
  end

  if outcome.success?
    self.next_command_name = outcome.result[:command]
    self.next_command_inputs = outcome.result[:inputs]
    self.next_command_raw_inputs = next_command_inputs

    outcome = validate_next_command_name

    if outcome.success?
      fetch_next_command_class

      if need_to_describe_next_command?
        simulate_describe_command
        return determine_next_command_and_inputs(retries, outcome)
      end

      if next_command_has_inputs?
        outcome = validate_next_command_inputs

        unless outcome.success?
          # TODO: test this path
          # simplecov:disable
          log_command_outcome(
            command_name: next_command_name,
            inputs: next_command_inputs,
            outcome:
          )

          simulate_describe_command

          determine_next_command_and_inputs(retries - 1, outcome)
          # simplecov:enable
        end
      else
        self.next_command_inputs = {}
        self.next_command_raw_inputs = next_command_inputs
      end
    else
      log_command_outcome(
        command_name: next_command_name,
        inputs: next_command_inputs,
        outcome:,
        result: nil
      )

      determine_next_command_and_inputs(retries - 1, outcome)
    end
  else
    log_command_outcome(
      command_name: determine_command.class.full_command_name,
      inputs: determine_command.inputs&.except(:context),
      outcome:,
      result: outcome.result || determine_command.raw_result
    )

    determine_next_command_and_inputs(retries - 1, outcome)
  end
end

#empty_attributes?(type) ⇒ Boolean

Returns:

  • (Boolean)


513
514
515
# File 'src/foobara/agent/accomplish_goal.rb', line 513

def empty_attributes?(type)
  type.extends_type?(BuiltinTypes[:attributes]) && type.element_types.empty?
end

#execute ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'src/foobara/agent/accomplish_goal.rb', line 39

def execute
  unless list_commands_already_ran?
    simulate_describe_list_commands_command
    simulate_list_commands_run
  end

  until mission_accomplished? or given_up? or killed?
    increment_command_calls
    check_if_too_many_calls

    determine_next_command_and_inputs

    run_next_command
  end

  if given_up?
    add_given_up_error
  end

  build_result
end

#fetch_next_command_class ⇒ Object



268
269
270
# File 'src/foobara/agent/accomplish_goal.rb', line 268

def fetch_next_command_class
  self.next_command_class = agent.transformed_command_from_name(next_command_name)
end

#final_result_type_from_declaration ⇒ Object



472
473
474
475
476
477
478
479
480
481
482
483
# File 'src/foobara/agent/accomplish_goal.rb', line 472

def final_result_type_from_declaration
  return @final_result_type_from_declaration if defined?(@final_result_type_from_declaration)

  @final_result_type_from_declaration = if final_result_type
                                          if final_result_type.is_a?(Types::Type)
                                            final_result_type
                                          else
                                            domain = result_type.created_in_namespace.foobara_domain
                                            domain.foobara_type_from_declaration(final_result_type)
                                          end
                                        end
end

#give_up!(message) ⇒ Object



463
464
465
466
# File 'src/foobara/agent/accomplish_goal.rb', line 463

def give_up!(message)
  self.given_up = true
  self.final_message = message
end

#given_up? ⇒ Boolean

Returns:

  • (Boolean)


553
554
555
# File 'src/foobara/agent/accomplish_goal.rb', line 553

def given_up?
  given_up
end

#increment_command_calls ⇒ Object



352
353
354
355
# File 'src/foobara/agent/accomplish_goal.rb', line 352

def increment_command_calls
  self.command_calls ||= -1
  self.command_calls += 1
end

#kill! ⇒ Object



459
460
461
# File 'src/foobara/agent/accomplish_goal.rb', line 459

def kill!
  self.killed = true
end

#killed? ⇒ Boolean

Returns:

  • (Boolean)


557
558
559
# File 'src/foobara/agent/accomplish_goal.rb', line 557

def killed?
  killed
end

#list_commands_already_ran? ⇒ Boolean

Returns:

  • (Boolean)


66
67
68
# File 'src/foobara/agent/accomplish_goal.rb', line 66

def list_commands_already_ran?
  context.command_log.any? { |log_entry| log_entry.command_name =~ /\bListCommands\z/ }
end

#log_command_code(command_name:, inputs:) ⇒ Object



420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
# File 'src/foobara/agent/accomplish_goal.rb', line 420

def log_command_code(command_name:, inputs:)
  if verbose?
    args = if next_command_inputs.nil? || next_command_inputs.empty?
             ""
           else
             s = next_command_inputs.to_s

             if s =~ /\A\{(.*)}\z/
               "(#{::Regexp.last_match(1)})"
             else
               # simplecov:disable
               raise "Unexpected next_command_inputs: #{next_command_inputs}"
               # simplecov:enable
             end
           end

    agent_name = agent.agent_name
    prefix = if agent_name && !agent_name.empty?
               "#{agent_name}<#{llm_model}>: "
             else
               # Not setting an agent_name results in non-determinism in NotifyUser... command
               # namespace. This results in problems in the test suite making this code path a little
               # harder to test indirectly.
               # simplecov:disable
               ""
               # simplecov:enable
             end

    (io_out || $stdout).puts "#{prefix}#{next_command_name}.run#{args}"
  end
end

#log_command_outcome(command: nil, command_name: nil, inputs: nil, outcome: nil, result: nil, log_command_code: true) ⇒ Object



368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
# File 'src/foobara/agent/accomplish_goal.rb', line 368

def log_command_outcome(command: nil,
                        command_name: nil,
                        inputs: nil,
                        outcome: nil,
                        result: nil,
                        log_command_code: true)
  if command
    command_name ||= command.class.full_command_name
    inputs ||= command.raw_inputs
    outcome ||= command.outcome
  end

  if outcome&.success?
    result ||= outcome.result
  end

  outcome_hash = { success: outcome.success? }

  if outcome.success? || result
    outcome_hash[:result] = result
  end

  unless outcome.success?
    outcome_hash[:errors_hash] = outcome.errors_hash
  end

  log_entry = CommandLogEntry.new(
    command_name:,
    inputs:,
    outcome: outcome_hash
  )

  context.command_log << log_entry

  if verbose?
    if log_command_code
      # TODO: test this code path hmmm
      # simplecov:disable
      self.log_command_code(command_name:, inputs:)
      # simplecov:enable
    end

    unless log_entry.success?
      # simplecov:disable
      (io_err || $stderr).puts(
        "Command #{log_entry.command_name} failed:\n#{log_entry.errors_hash}"
      )
      # simplecov:enable
    end
  end
end

#mission_accomplished!(final_result, message) ⇒ Object

TODO: these are awkwardly called from outside. Come up with a better solution.



453
454
455
456
457
# File 'src/foobara/agent/accomplish_goal.rb', line 453

def mission_accomplished!(final_result, message)
  self.mission_accomplished = true
  self.final_result = final_result
  self.final_message = message
end

#mission_accomplished? ⇒ Boolean

Returns:

  • (Boolean)


549
550
551
# File 'src/foobara/agent/accomplish_goal.rb', line 549

def mission_accomplished?
  mission_accomplished
end

#need_to_describe_next_command? ⇒ Boolean

Returns:

  • (Boolean)


521
522
523
524
525
526
527
528
529
# File 'src/foobara/agent/accomplish_goal.rb', line 521

def need_to_describe_next_command?
  return false if command_described?(next_command_name)
  return false if next_command_name == DescribeCommand.full_command_name
  return true if next_command_has_inputs?

  # check if inputs were unexpectedly given for a command that doesn't need them,
  # in which case we should describe it
  next_command_inputs && !next_command_inputs.empty?
end

#next_command_has_inputs? ⇒ Boolean

Returns:

  • (Boolean)


272
273
274
275
# File 'src/foobara/agent/accomplish_goal.rb', line 272

def next_command_has_inputs?
  type = next_command_class.inputs_type
  type && !empty_attributes?(type)
end

#record_llm_call_timestamp ⇒ Object



541
542
543
# File 'src/foobara/agent/accomplish_goal.rb', line 541

def record_llm_call_timestamp
  llm_call_timestamps.unshift(Time.now)
end

#run_next_command ⇒ Object



277
278
279
280
281
282
283
284
285
286
287
288
289
# File 'src/foobara/agent/accomplish_goal.rb', line 277

def run_next_command
  log_command_code(command_name: next_command_name, inputs: next_command_inputs)

  self.command_response = agent.run(
    full_command_name: next_command_name,
    inputs: next_command_inputs,
    action: "run"
  )

  self.command_outcome = command_response.outcome

  log_command_outcome(command: command_response.command, log_command_code: false)
end

#simulate_describe_command(command_name = next_command_name) ⇒ Object



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'src/foobara/agent/accomplish_goal.rb', line 89

def simulate_describe_command(command_name = next_command_name)
  old_next_command_name = next_command_name
  old_next_command_inputs = next_command_inputs
  old_next_command_raw_inputs = next_command_raw_inputs
  old_next_command_class = next_command_class

  self.next_command_name = DescribeCommand.full_command_name
  self.next_command_inputs = { command_name: }
  self.next_command_raw_inputs = next_command_inputs

  fetch_next_command_class

  run_next_command

  self.next_command_name = old_next_command_name
  self.next_command_inputs = old_next_command_inputs
  self.next_command_raw_inputs = old_next_command_raw_inputs
  self.next_command_class = old_next_command_class
end

#simulate_describe_command_run_for_all_commands ⇒ Object



109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'src/foobara/agent/accomplish_goal.rb', line 109

def simulate_describe_command_run_for_all_commands
  # TODO: currently not using this code path. Unclear if it is worth it.
  # simplecov:disable
  return if context.command_log.size > 1

  ListCommands.run!(command_connector: agent)[:user_provided_commands].each do |full_command_name|
    next if command_described?(full_command_name)

    self.next_command_name = DescribeCommand.full_command_name
    self.next_command_inputs = { command_name: full_command_name }
    self.next_command_raw_inputs = next_command_inputs
    fetch_next_command_class

    run_next_command
  end
  # simplecov:enable
end

#simulate_describe_list_commands_command ⇒ Object



80
81
82
83
84
85
86
87
# File 'src/foobara/agent/accomplish_goal.rb', line 80

def simulate_describe_list_commands_command
  self.next_command_name = DescribeCommand.full_command_name
  self.next_command_inputs = { command_name: ListCommands.full_command_name }
  self.next_command_raw_inputs = next_command_inputs
  fetch_next_command_class

  run_next_command
end

#simulate_list_commands_run ⇒ Object



70
71
72
73
74
75
76
77
78
# File 'src/foobara/agent/accomplish_goal.rb', line 70

def simulate_list_commands_run
  self.next_command_name = ListCommands.full_command_name
  self.next_command_raw_inputs = nil
  self.next_command_inputs = nil

  fetch_next_command_class

  run_next_command
end

#validate_next_command_inputs ⇒ Object



251
252
253
254
255
256
257
258
# File 'src/foobara/agent/accomplish_goal.rb', line 251

def validate_next_command_inputs
  inputs_type = next_command_class.inputs_type

  NestedTransactionable.with_needed_transactions_for_type(inputs_type) do
    inputs = next_command_inputs.nil? ? {} : next_command_inputs
    inputs_type.process_value(inputs)
  end
end

#validate_next_command_name ⇒ Object



228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
# File 'src/foobara/agent/accomplish_goal.rb', line 228

def validate_next_command_name
  if next_command_name.is_a?(::String)
    command_class = agent.transformed_command_from_name(next_command_name)

    if command_class
      self.next_command_name = command_class.full_command_name

      return Outcome.success(next_command_name)
    end
  end

  outcome = command_name_type.process_value(next_command_name)

  if outcome.success?
    # TODO: figure out a way to hit this path in the test suite
    # simplecov:disable
    self.next_command_name = outcome.result
    # simplecov:enable
  end

  outcome
end

#verbose? ⇒ Boolean

Returns:

  • (Boolean)


517
518
519
# File 'src/foobara/agent/accomplish_goal.rb', line 517

def verbose?
  verbose
end