Class: DSPy::LM::Strategies::EnhancedPromptingStrategy
- Inherits:
-
BaseStrategy
- Object
- BaseStrategy
- DSPy::LM::Strategies::EnhancedPromptingStrategy
show all
- Extended by:
- T::Sig
- Defined in:
- lib/dspy/lm/strategies/enhanced_prompting_strategy.rb
Overview
Enhanced prompting strategy that works with any LLM Adds explicit JSON formatting instructions to improve reliability
Instance Method Summary
collapse
#handle_error, #initialize
Instance Method Details
#available? ⇒ Boolean
14
15
16
17
|
# File 'lib/dspy/lm/strategies/enhanced_prompting_strategy.rb', line 14
def available?
true
end
|
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
|
# File 'lib/dspy/lm/strategies/enhanced_prompting_strategy.rb', line 56
def (response)
return nil if response.content.nil?
content = response.content.strip
if content.include?('```json')
json_content = content.split('```json').last.split('```').first.strip
return json_content if valid_json?(json_content)
elsif content.include?('```')
code_block = content.split('```')[1]
if code_block
json_content = code_block.strip
return json_content if valid_json?(json_content)
end
end
return content if valid_json?(content)
json_match = content.match(/\{[\s\S]*\}|\[[\s\S]*\]/)
if json_match
json_content = json_match[0]
return json_content if valid_json?(json_content)
end
nil
end
|
#name ⇒ Object
25
26
27
|
# File 'lib/dspy/lm/strategies/enhanced_prompting_strategy.rb', line 25
def name
"enhanced_prompting"
end
|
#prepare_request(messages, request_params) ⇒ Object
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
# File 'lib/dspy/lm/strategies/enhanced_prompting_strategy.rb', line 30
def prepare_request(messages, request_params)
return if messages.empty?
output_schema = signature_class.output_json_schema
last_user_idx = messages.rindex { |msg| msg[:role] == "user" }
return unless last_user_idx
original_content = messages[last_user_idx][:content]
enhanced_content = enhance_prompt_with_json_instructions(original_content, output_schema)
messages[last_user_idx][:content] = enhanced_content
if messages.none? { |msg| msg[:role] == "system" }
messages.unshift({
role: "system",
content: "You are a helpful assistant that always responds with valid JSON when requested."
})
end
end
|
#priority ⇒ Object
20
21
22
|
# File 'lib/dspy/lm/strategies/enhanced_prompting_strategy.rb', line 20
def priority
50 end
|