Module: DSPy::Teleprompt::Utils

Extended by:
T::Sig
Defined in:
lib/dspy/teleprompt/utils.rb

Overview

Bootstrap utilities for MIPROv2 optimization Handles few-shot example generation and candidate program evaluation

Defined Under Namespace

Classes: BootstrapConfig, BootstrapResult

Class Method Summary collapse

Class Method Details

.create_candidate_sets(successful_examples, config) ⇒ Object



293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
# File 'lib/dspy/teleprompt/utils.rb', line 293

def self.create_candidate_sets(successful_examples, config)
  return [] if successful_examples.empty?

  # Use DataHandler for efficient sampling
  data_handler = DataHandler.new(successful_examples)
  set_size = [config.max_bootstrapped_examples, successful_examples.size].min

  # Create candidate sets efficiently
  candidate_sets = data_handler.create_candidate_sets(
    config.num_candidate_sets,
    set_size,
    random_state: 42  # For reproducible results
  )

  candidate_sets
end

.create_n_fewshot_demo_sets(program, trainset, config: BootstrapConfig.new, metric: nil) ⇒ Object



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
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/dspy/teleprompt/utils.rb', line 105

def self.create_n_fewshot_demo_sets(program, trainset, config: BootstrapConfig.new, metric: nil)
  DSPy::Context.with_span(
    operation: 'optimization.bootstrap_start',
    'dspy.module' => 'Bootstrap',
    'bootstrap.trainset_size' => trainset.size,
    'bootstrap.max_examples' => config.max_bootstrapped_examples,
    'bootstrap.num_candidate_sets' => config.num_candidate_sets
  ) do
    # Convert to typed examples if needed
    typed_examples = ensure_typed_examples(trainset)
    
    # Generate successful examples through bootstrap
    successful_examples, failed_examples = generate_successful_examples(
      program, 
      typed_examples, 
      config,
      metric
    )

    # Create candidate sets from successful examples
    candidate_sets = create_candidate_sets(successful_examples, config)

    # Gather statistics
    statistics = {
      total_trainset: trainset.size,
      successful_count: successful_examples.size,
      failed_count: failed_examples.size,
      success_rate: successful_examples.size.to_f / (successful_examples.size + failed_examples.size),
      candidate_sets_created: candidate_sets.size,
      average_set_size: candidate_sets.empty? ? 0 : candidate_sets.map(&:size).sum.to_f / candidate_sets.size
    }

    emit_bootstrap_complete_event(statistics)

    BootstrapResult.new(
      candidate_sets: candidate_sets,
      successful_examples: successful_examples,
      failed_examples: failed_examples,
      statistics: statistics
    )
  end
end

.create_successful_bootstrap_example(original_example, prediction) ⇒ Object



317
318
319
320
321
322
323
324
325
326
327
328
329
330
# File 'lib/dspy/teleprompt/utils.rb', line 317

def self.create_successful_bootstrap_example(original_example, prediction)
  # Convert prediction to FewShotExample format
  DSPy::Example.new(
    signature_class: original_example.signature_class,
    input: original_example.input_values,
    expected: prediction.to_h,
    id: "bootstrap_#{original_example.id || SecureRandom.uuid}",
    metadata: {
      source: "bootstrap",
      original_expected: original_example.expected_values,
      bootstrap_timestamp: Time.now.iso8601
    }
  )
end

.default_metric_for_examples(examples) ⇒ Object



335
336
337
338
339
340
341
# File 'lib/dspy/teleprompt/utils.rb', line 335

def self.default_metric_for_examples(examples)
  if examples.first.is_a?(DSPy::Example)
    proc { |example, prediction| example.matches_prediction?(prediction) }
  else
    nil
  end
end

.emit_bootstrap_complete_event(statistics) ⇒ Object



345
346
347
348
349
350
351
352
353
# File 'lib/dspy/teleprompt/utils.rb', line 345

def self.emit_bootstrap_complete_event(statistics)
  DSPy.log('optimization.bootstrap_complete', **{
    'bootstrap.successful_count' => statistics[:successful_count],
    'bootstrap.failed_count' => statistics[:failed_count],
    'bootstrap.success_rate' => statistics[:success_rate],
    'bootstrap.candidate_sets_created' => statistics[:candidate_sets_created],
    'bootstrap.average_set_size' => statistics[:average_set_size]
  })
end

.emit_bootstrap_example_event(index, success, error) ⇒ Object



357
358
359
360
361
362
363
# File 'lib/dspy/teleprompt/utils.rb', line 357

def self.emit_bootstrap_example_event(index, success, error)
  DSPy.log('optimization.bootstrap_example', **{
    'bootstrap.example_index' => index,
    'bootstrap.success' => success,
    'bootstrap.error' => error
  })
end

.ensure_typed_examples(examples) ⇒ Object

Raises:

  • (ArgumentError)


217
218
219
220
221
# File 'lib/dspy/teleprompt/utils.rb', line 217

def self.ensure_typed_examples(examples)
  return examples if examples.all? { |ex| ex.is_a?(DSPy::Example) }
  
  raise ArgumentError, "All examples must be DSPy::Example instances. Legacy format support has been removed. Please convert your examples to use the structured format with :input and :expected keys."
end

.eval_candidate_program(program, examples, config: BootstrapConfig.new, metric: nil) ⇒ Object



157
158
159
160
161
162
163
164
# File 'lib/dspy/teleprompt/utils.rb', line 157

def self.eval_candidate_program(program, examples, config: BootstrapConfig.new, metric: nil)
  # Use minibatch evaluation for large datasets
  if examples.size > config.minibatch_size
    eval_candidate_program_minibatch(program, examples, config, metric)
  else
    eval_candidate_program_full(program, examples, config, metric)
  end
end

.eval_candidate_program_full(program, examples, config, metric) ⇒ Object



200
201
202
203
204
205
206
207
208
209
210
211
# File 'lib/dspy/teleprompt/utils.rb', line 200

def self.eval_candidate_program_full(program, examples, config, metric)
  # Create evaluator with proper configuration
  evaluator = DSPy::Evaluate.new(
    program,
    metric: metric || default_metric_for_examples(examples),
    num_threads: config.num_threads,
    max_errors: config.max_errors
  )

  # Run evaluation
  evaluator.evaluate(examples, display_progress: false)
end

.eval_candidate_program_minibatch(program, examples, config, metric) ⇒ Object



175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
# File 'lib/dspy/teleprompt/utils.rb', line 175

def self.eval_candidate_program_minibatch(program, examples, config, metric)
  DSPy::Context.with_span(
    operation: 'optimization.minibatch_evaluation',
    'dspy.module' => 'Bootstrap',
    'minibatch.total_examples' => examples.size,
    'minibatch.size' => config.minibatch_size,
    'minibatch.num_batches' => (examples.size.to_f / config.minibatch_size).ceil
  ) do
    # Randomly sample a minibatch for evaluation
    sample_size = [config.minibatch_size, examples.size].min
    sampled_examples = examples.sample(sample_size)
    
    eval_candidate_program_full(program, sampled_examples, config, metric)
  end
end

.generate_successful_examples(program, examples, config, metric) ⇒ Object



232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
# File 'lib/dspy/teleprompt/utils.rb', line 232

def self.generate_successful_examples(program, examples, config, metric)
  successful = []
  failed = []
  error_count = 0

  # Use DataHandler for efficient shuffling
  data_handler = DataHandler.new(examples)
  shuffled_examples = data_handler.shuffle(random_state: 42)

  shuffled_examples.each_with_index do |example, index|
    break if successful.size >= config.max_labeled_examples
    break if error_count >= config.max_errors

    begin
      # Run program on example input
      prediction = program.call(**example.input_values)
      
      # Check if prediction matches expected output
      if metric
        success = metric.call(example, prediction.to_h)
      else
        success = example.matches_prediction?(prediction.to_h)
      end

      if success
        # Create a new example with the successful prediction as reasoning/context
        successful_example = create_successful_bootstrap_example(example, prediction)
        successful << successful_example
        
        emit_bootstrap_example_event(index, true, nil)
      else
        failed << example
        emit_bootstrap_example_event(index, false, "Prediction did not match expected output")
      end

    rescue => error
      error_count += 1
      failed << example
      emit_bootstrap_example_event(index, false, error.message)
      
      # Log error but continue processing
      DSPy.logger.warn("Bootstrap error on example #{index}: #{error.message}")
      
      # Stop if too many errors
      if error_count >= config.max_errors
        DSPy.logger.error("Too many bootstrap errors (#{error_count}), stopping early")
        break
      end
    end
  end

  [successful, failed]
end

.infer_signature_class(examples) ⇒ Object



367
368
369
370
371
372
373
374
375
376
377
378
379
# File 'lib/dspy/teleprompt/utils.rb', line 367

def self.infer_signature_class(examples)
  return nil if examples.empty?

  first_example = examples.first
  
  if first_example.is_a?(DSPy::Example)
    first_example.signature_class
  elsif first_example.is_a?(Hash) && first_example[:signature_class]
    first_example[:signature_class]
  else
    nil
  end
end