Class: DSPy::LM::StrategySelector

Inherits:
Object
  • Object
show all
Extended by:
T::Sig
Defined in:
lib/dspy/lm/strategy_selector.rb

Overview

Selects the best JSON extraction strategy based on the adapter and capabilities

Constant Summary collapse

STRATEGIES =

Available strategies in order of registration

[
  Strategies::OpenAIStructuredOutputStrategy,
  Strategies::AnthropicToolUseStrategy,
  Strategies::AnthropicExtractionStrategy,
  Strategies::EnhancedPromptingStrategy
].freeze

Instance Method Summary collapse

Constructor Details

#initialize(adapter, signature_class) ⇒ StrategySelector

Returns a new instance of StrategySelector.



25
26
27
28
29
# File 'lib/dspy/lm/strategy_selector.rb', line 25

def initialize(adapter, signature_class)
  @adapter = adapter
  @signature_class = signature_class
  @strategies = build_strategies
end

Instance Method Details

#available_strategiesObject



63
64
65
# File 'lib/dspy/lm/strategy_selector.rb', line 63

def available_strategies
  @strategies.select(&:available?)
end

#selectObject



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
# File 'lib/dspy/lm/strategy_selector.rb', line 33

def select
  # Allow manual override via configuration
  if DSPy.config.structured_outputs.strategy
    strategy = select_strategy_from_preference(DSPy.config.structured_outputs.strategy)
    return strategy if strategy&.available?
    
    # If strict strategy not available, fall back to compatible for Strict preference
    if is_strict_preference?(DSPy.config.structured_outputs.strategy)
      compatible_strategy = find_strategy_by_name("enhanced_prompting")
      return compatible_strategy if compatible_strategy&.available?
    end
    
    DSPy.logger.warn("No available strategy found for preference '#{DSPy.config.structured_outputs.strategy}'")
  end

  # Select the highest priority available strategy
  available_strategies = @strategies.select(&:available?)
  
  if available_strategies.empty?
    raise "No JSON extraction strategies available for #{@adapter.class}"
  end

  selected = available_strategies.max_by(&:priority)
  
  DSPy.logger.debug("Selected JSON extraction strategy: #{selected.name}")
  selected
end

#strategy_available?(strategy_name) ⇒ Boolean

Returns:

  • (Boolean)


69
70
71
72
# File 'lib/dspy/lm/strategy_selector.rb', line 69

def strategy_available?(strategy_name)
  strategy = find_strategy_by_name(strategy_name)
  strategy&.available? || false
end